RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题

全部问题

Martin Hope
Lennet8002
Asked: 2025-03-23 02:48:06 +0000 UTC

使用 Python 和 Postgresql 开发 Telegram 机器人

  • 5

大家好!我决定在 aiogram3 和 postgresql 上创建一个项目,但是却走进了死胡同。该机器人的任务是接受关键词并使用它们在数据库中搜索信息。也就是说,如果我写/search 80那么它应该通过这个参数给出两个玩家的值(数据库在下面,在这种情况下是lennet和pico),但它只给出1个人的信息。我考虑尝试通过 for 循环来完成此操作,但没有成功。这是基础:在此处输入图片描述

代码如下:

@dp.message(Command('search'))
async def search(message: Message):
    #тут будет поиск в бд
    arg =  message.text.split()  #получаем данные юзера
    args = str(arg.pop(1))  #удаляем элемент т.к arg содержит в себе /search
    try:
        connection = psycopg2.connect(  # конектимся к бд
            host="127.0.0.1",
            user="postgres",
            password="staff",
            database="wow_klass№2",
            port="5432"
        )
        connection.autocommit = True  
        zapros  = f"SELECT * FROM spek WHERE nikname = '{args}' OR class = '{args}' OR spek = '{args}' OR profa = '{args}' OR lvl = '{args}';"
        int = f" SELECT COUNT(*) FROM spek WHERE nikname = '{args}' OR class = '{args}' OR spek = '{args}' OR profa = '{args}' OR lvl = '{args}';"
        ##### запрос  в бд
        with connection.cursor() as iner:
            iner.execute(int)
            integer = iner.fetchone()
        with connection.cursor() as cursor:
            cursor.execute(zapros)
            #закончу тут, появился норм запрос и ответ, осталось реализовать больше 1 участника
            tuple = cursor.fetchone()
            nic = str(tuple[0])
            clas = str(tuple[1])
            spek = str(tuple[2])
            prof = str(tuple[3])
            lvl = str(tuple[4])
            await message.answer(f"Ник игрока: {nic}. \nКласс: {clas}. \nСпек: {spek}. \nПрофесия: {prof}. \nlvl: {lvl}")
    except Exception as _ex:
        print(_ex)
    finally:
        if connection:
            connection.close()
            print("Отсоеденился успешно")
python
  • 1 个回答
  • 30 Views
Martin Hope
eccs0103
Asked: 2025-03-22 23:54:52 +0000 UTC

try-catch 未捕获错误

  • 6

描述

我写了一个简单的附录:

declare global {
    interface Promise<T> {
        isFulfilled: Promise<boolean>;
    }
}

Object.defineProperty(Promise.prototype, "isFulfilled", {
    async get<T>(this: Promise<T>): Promise<boolean> {
        const symbol = Promise.resolve(Symbol());
        try {
            const result = (await Promise.race([this, symbol]) !== symbol);
            console.log("after promise");
            return result;
        } catch {
            console.log(`catch`);
            return true;
        }
    }
});

const promise = new Promise<void>(async (resolve) => {
    throw new Error(`Test error`);
});
console.log(await (promise.isFulfilled));

export { };

我们看到,Promise 的执行发生在 try 中,并没有超越它。这种情况下,如果出现错误,try应该捕获它,并去catch。
我收到一个错误并且尝试继续:

问题

为什么会发生这种情况?
我该如何修复我的功能?

typescript
  • 1 个回答
  • 29 Views
Martin Hope
Степа
Asked: 2025-03-22 20:31:52 +0000 UTC

如何在记事本中打开文件?

  • 6

您需要打开该文件file_doc.txt,但不仅仅是读取它,而是在记事本中打开它。

我该如何做?

代码:

print('Вы хотите открыть файл "file_doc.txt"? (да/нет)')
inp = input()
if inp == "да":
    # Здесь нужно как-то открыть файл
else:
    print("Хорошо")
python
  • 1 个回答
  • 31 Views
Martin Hope
Алексей
Asked: 2025-03-22 20:07:49 +0000 UTC

express js 数据传递到所有路由获取

  • 5

问题是如何正确地将相同的数据传输到所有路​​由,以免写出类似这样的内容:

router.route('/home')
    .get((req, res) => res.render('home', {toast: res.flash('toast')}))
router.route('/email')
    .get((req, res) => res.render('email', {toast: res.flash('toast')}))
router.route('/contact')
    .get((req, res) => res.render('contact', {toast: res.flash('toast')}))

据我了解,在中间件级别实现这一点是正确的,但是如何实现呢?最小任务是转发到所有路由,最大任务是只获取请求

node.js
  • 2 个回答
  • 33 Views
Martin Hope
lil_ankkk
Asked: 2025-03-22 19:49:19 +0000 UTC

输出 XML 树中特定标签的元素

  • 7

有一棵xml树,其内容大致如下:

<uslist>
    <spisok id="1" name="Важные дела" />
    <act name="Важное дело" />
    <act name="Ещё важное дело" />

    <spisok id="2" name="Не очень важные дела" />
    <act name="Неважное дело" />
    <act name="Ещё неважное дело" />
</uslist>

act我需要输出所选列表的元素。也就是说如何输出id=2的标签元素呢?

@bot.callback_query_handler(func=lambda call: call.data.startswith("list_"))
def list_selected(call):
    list_id = call.data[5:]

try:
    root = lxml.etree.parse('remain.xml') 
except FileNotFoundError:
    print("Файл remain.xml не найден.") # Логирование в консоль
    return None # Возвращаем None в случае ошибки

acts = []

for result in root.xpath(f"//spisok[@id='{list_id}']"):
        for act_element in result.findall('act'):
            act_name = act_element.get('name')
            acts.append(act_name) 

if not acts:
    bot.send_message(
        call.from_user.id,
        "У вас пока нет дел в этом списке", 
        reply_markup=list_menu
    )
    list_of_acts = types.InlineKeyboardMarkup(row_width=2)

for act_name in acts:
    list_of_acts.add(
        types.InlineKeyboardButton(
            text=act_name, 
            callback_data=f"act_{act_name}"
        )
    )
tree.write("remain.xml", encoding="utf-8")

我用自己的头脑想出了这个解决办法,但它不起作用。

python
  • 1 个回答
  • 23 Views
上一页
下一页

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5