再会。
我是一名新手开发人员,这是我在 StackOverflow 上的第一个问题,使用 MySQL DBMS、mysql.connector 制作一个 python 机器人。
现在我每次需要更改数据库时都连接到数据库,是否可以这样做一次而不每次都重复这段代码?
另外,我想知道是否可以像这样在bot的源代码中留下密码,将其上传到托管,是否安全?
进一步的代码:
@bot.message_handler(func=lambda m: True)
def echo_all(message):
user_id = message.from_user.id
if message.text == 'Создать анкету':
try:
with connect(
host="localhost",
# user=input("Введите имя пользователя: "),
# password=getpass("Введите пароль: "),
user="newuser",
password="255****",
database="forms"
) as connection:
select_forms_query = '''
SELECT chat_id
FROM form
'''
get_user_form = f'''
SELECT name, years_old, title
FROM form
WHERE chat_id = {user_id}
'''
with connection.cursor() as cursor:
cursor.execute(select_forms_query)
result = cursor.fetchall()
if is_user_in_base(result, user_id):
cursor.execute(get_user_form)
user_form = cursor.fetchall()
user_form_out(user_form, user_id)
else:
print(user_id, "- user is not in database")
process_filling_form(user_id)
except Error as e:
print(e)
如何缩短这个区域with connect (...) as connection (...)?
1 个回答