当创建大型项目并将代码分为不同的文件时,我想知道:像 atmega 和 esp 这样的 gem 上的微控制器是否有int main(){while(1){//код} }任何陷阱?void loop(){//код}那么替代品是什么void setup(){}?
我向该网站发出了后期请求并收到了很多回复。问题是它不是经典的 json 格式,而是这样的:
event:conversation.chat.created
data:{"id":"xxxxxxxx","conversation_id":"xxxxxx","bot_id":"Xxxxxxx","created_at":xxxxxxx,"last_error":{"code":0,"msg":""},"status":"created","usage":{"token_count":0,"output_count":0,"input_count":0}}
event:conversation.chat.in_progress
data:{"id":"xxxxxxxxx","conversation_id":"xxxxxxxxxxx","bot_id":"xxxxxxxxxxx","created_at":xxxxxxxx,"last_error":{"code":0,"msg":""},"status":"in_progress","usage":{"token_count":0,"output_count":0,"input_count":0}}
#Заменил значения на 'XXXX'
服务器响应超过 9-10 个,并且全部在一个响应中收到。 Postman 通常会划分它们,而 Python 不会:
当我尝试将所有这些转换为 json via 时responce.json(),它开始给出错误json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
尝试翻译成文本导致我无法添加逗号、删除不必要的\n等等。我应该怎么办?
我编写了一个可以读取数据并将数据写入 .yaml 文件的程序。但现在我面临着将重置设置功能组织为标准的问题。我不知道如何在我的代码中最好地做到这一点...组织这样一个易于理解且简洁的函数的最佳方法是什么?
主要代码文件(settings.py):
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from enum import Enum
import yaml
from src.settings.default_settings import JetInjectorConstant, CentrifugalInjectorConstant
class ListNameSettingsFile(Enum):
"""
РУС: Список файлов конфигурации
ENG: List of configuration files
"""
LIST_NAME_SETTINGS_FILE = ["injector_settings"]
@dataclass(frozen=True)
class Settings(ABC):
"""
РУС: Основной класс для обработки файлов конфигурации
ENG: The main class for processing configuration files
"""
@staticmethod
def get_root_dir():
"""
РУС: Директория установки ПО
ENG: The software installation directory
"""
return Path(__file__).absolute().parent
@abstractmethod
def get_data_for_recording(self) -> dict:
"""
РУС: Получение данных для загрузки в файл конфигурации
ENG: Getting data to upload to a configuration file
"""
raise NotImplementedError("Данные настроек не загружены")
@abstractmethod
def name_settings_file(self) -> str:
"""
РУС: Получение имени файла конфигурации
ENG: Getting the name of the configuration file
"""
raise NotImplementedError("Имя файла настроек не загружено")
@property
def save_settings(self) -> None:
"""
РУС: Запись констант в файл конфигурации
ENG: Writing constants to a configuration file
"""
with open((self.get_root_dir() / "data").joinpath(self.name_settings_file() + ".yaml"), "w") as outfile:
new_dump = yaml.dump(self.get_data_for_recording())
outfile.write(new_dump)
return None
@property
def read_settings(self) -> dict:
"""
РУС: Чтение констант из файла конфигурации
ENG: Reading constants from a configuration file
"""
with open((self.get_root_dir() / "data").joinpath(self.name_settings_file() + ".yaml"), "r") as stream:
read_date = yaml.safe_load(stream)
return read_date
@dataclass(frozen=True)
class InjectorSettings(Settings):
"""
РУС: Класс констант для проведения расчетов
ENG: A class of constants for performing calculations
"""
laminar: float | None = None
turbulent: float | None = None
right_angle: float | None = None
def get_data_for_recording(self) -> dict:
"""
РУС: Загрузка констант для расчетов
ENG: Loading constants for calculations
"""
injector_settings = {
"reynolds": {"laminar": self.laminar, "turbulent": self.turbulent},
"right_angle": self.right_angle,
}
return injector_settings
def name_settings_file(self) -> str:
"""
РУС: Передача имени файла конфигурации
ENG: Passing the name of the configuration file
"""
return ListNameSettingsFile.LIST_NAME_SETTINGS_FILE.value[0]
具有标准设置的文件(default_settings.py):
from enum import Enum
class JetInjectorConstant(Enum):
"""Стандартные значение констант струйной """
LAMINAR = 2000
TURBULENT = 10_000
class CentrifugalInjectorConstant(Enum):
"""Стандартные значение констант центробежной форсунки"""
RIGHT_ANGLE = 90
更新:
在这个项目结构中,我们不是将数据存储在文件中default_settings.yaml,而是将数据存储在文件中default_settings.py,如果不小心删除了这样的文件.yaml,这将导致软件彻底崩溃,如果在程序内部发现了这些数据,将能够恢复其运作。
该文件settings.yaml将存储负责计算边界和启动程序的设置的设置。它们在程序启动时使用一次,并且不会进一步使用。也就是说,如果您在运行期间更改它们,这不会以任何方式影响程序的运行。
需要设置重置系统,以便如果输入了错误的数据,可以返回到程序安装状态(标准设置)。如果在尝试打开文件时,由于文件结构损坏或与无法打开或读取文件相关的其他错误而导致程序无法执行此操作,也会激活重置系统。
bot.send_message 方法不起作用。
写道
名称“bot”未定义
我查遍了,还是没找到答案=(
主要.py:
import asyncio
import logging
from aiogram import Bot, Dispatcher
from aiogram.fsm.storage.memory import MemoryStorage
import handlers
async def main():
bot = Bot(token="7137.....")
dp = Dispatcher(storage=MemoryStorage())
dp.include_router(handlers.router)
await bot.delete_webhook(drop_pending_updates=True)
await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types())
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
asyncio.run(main())
处理程序.py:
from aiogram import types, F, Router
from aiogram.filters import Command
router = Router()
@router.message(Command("start"))
async def cmd_start(message: types.Message):
kb = [
[
types.KeyboardButton(text="Да"),
types.KeyboardButton(text="Нет")
],
]
keyboard = types.ReplyKeyboardMarkup(
keyboard=kb,
resize_keyboard=True,
input_field_placeholder="Присутствуете ли вы на работе?"
)
await message.answer('Присутствуете ли вы на работе? После нажатия на кнопку "Присутствую", подтвердите '
'отправку геометки пожалуйста.', reply_markup=keyboard)
@router.message(F.text.lower() == "нет")
async def not_working(message: types.Message):
await message.reply("не присутствую")
@router.message(F.text.lower() == "да")
async def working(message: types.Message):
await message.reply("присутствую")
@router.message(F.text)
async def not_registered(message: types.Message):
await bot.send_message(chat_id=message.from_user.id, text=message.text)
