我有以下项目结构
--some db:
--some db:
--alchemy:
-- __init__.py
--alembic:
-- versions
-- env.py
-- README.py
-- script.py
--migrations:
-- __init__.py
--models:
-- model_1
-- model_2
-- __init__.py
Run Code Online (Sandbox Code Playgroud)
我尝试通过 alembic 自动生成迁移。
我Base在__init__.py模型中的文件夹
import sqlalchemy as sa
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base, declared_attr
metadata = sa.MetaData()
Base = declarative_base(metadata=metadata)
Run Code Online (Sandbox Code Playgroud)
并导入这是 env.py
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from models import Base
config = context.config
fileConfig(config.config_file_name) …Run Code Online (Sandbox Code Playgroud) 我通过 sql alchemy 在数据库中创建记录。下一步是尝试将创建的对象的 id 捕获到另一个表中,该表在创建的对象上具有 fk (assign_resource_to_user) 。这是我的代码:
\n\nfrom dev_tools.models.user import User\nfrom dev_tools.models.resource Resource\n\nresource = Resource(\n code=self.message_body[\'code\'],\n description=self.message_body[\'description\'],\n crew_id=None,\n catalog_resource_type_id=self.message_body[\'catalog_resource_type_id\'],\n catalog_resource_status_id=self.message_body[\'catalog_resource_status_id\'],\n created_at=datetime.utcnow(),\n created_by=None,\n is_available=self.message_body[\'is_available\'],\n)\nself.db_session.add(resource)\nself.db_session.flush()\n\nassign_resource_to_user = self.db_session.query(\n User\n).filter(\n User.id == self.user_info.id\n).update(\n User.resource_id == resource.id\n)\nself.db_session.add(assign_resource_to_user)\nRun Code Online (Sandbox Code Playgroud)\n\n我有错误:
\n\nTraceback (most recent call last):\n File "/home/\xd0\x94\xd0\xbe\xd0\xba\xd1\x83\xd0\xbc\xd0\xb5\xd0\xbd\xd1\x82\xd1\x8b/project/ResourseManagment/rm-private-application-server/apps/controller/helpers/data_processing/action/custom/resource_from_a_user.py", line 227, in <module>\n resources.create_record_in_db()\n File "/home/\xd0\x94\xd0\xbe\xd0\xba\xd1\x83\xd0\xbc\xd0\xb5\xd0\xbd\xd1\x82\xd1\x8b/project/ResourseManagment/rm-private-application-server/apps/controller/helpers/data_processing/action/custom/resource_from_a_user.py", line 211, in create_record_in_db\n User.resource_id == resource.id\n File "/home/\xd0\x94\xd0\xbe\xd0\xba\xd1\x83\xd0\xbc\xd0\xb5\xd0\xbd\xd1\x82\xd1\x8b/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/orm/query.py", line 3486, in update\n File "/home/\xd0\x94\xd0\xbe\xd0\xba\xd1\x83\xd0\xbc\xd0\xb5\xd0\xbd\xd1\x82\xd1\x8b/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/orm/persistence.py", line 1334, in exec_\n File "/home/\xd0\x94\xd0\xbe\xd0\xba\xd1\x83\xd0\xbc\xd0\xb5\xd0\xbd\xd1\x82\xd1\x8b/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/orm/persistence.py", line 1405, in _do_pre_synchronize\n File "/home/\xd0\x94\xd0\xbe\xd0\xba\xd1\x83\xd0\xbc\xd0\xb5\xd0\xbd\xd1\x82\xd1\x8b/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/orm/persistence.py", line …Run Code Online (Sandbox Code Playgroud) 我有一些方法负责通过 id 从某个表中获取数据。该数据采用字符串格式。我需要将它们转换为 json。
async def my_async_method():
conn = await asyncpg.connect(**db_conf)
row = await conn.fetchrow(
'SELECT database.schema.table.some_table '
'FROM database.schema.some_table'
'WHERE database.schema.some_table.id = $1')
import_transaction = json.loads(row[0])
await conn.close()
loop = asyncio.get_event_loop()
loop.run_until_complete(my_async_method())
Run Code Online (Sandbox Code Playgroud)
在使用 asyncpg 的情况下,将数据从字符串转换为 json 的正确方法是什么?我将不胜感激您的帮助。
我尝试为我的项目实现 scrapy-puppeteer 库(https://pypi.org/project/scrapy-puppeteer/)
我根据库中的文档实现了 PuppeteerMiddleware
这是我运行的代码:
import asyncio
from twisted.internet import asyncioreactor
asyncioreactor.install(asyncio.get_event_loop())
import scrapy
from scrapy.crawler import CrawlerRunner
from twisted.internet import defer
from twisted.trial.unittest import TestCase
import scrapy_puppeteer
class ScrapyPuppeteerTestCase(TestCase):
"""Test case for the ``scrapy-puppeteer`` package"""
class PuppeteerSpider(scrapy.Spider):
name = 'puppeteer_crawl_spider'
allowed_domains = ['codesandbox.io']
custom_settings = {
'DOWNLOADER_MIDDLEWARES': {
'scrapy_puppeteer.PuppeteerMiddleware': 800
}
}
items = []
def start_requests(self):
yield scrapy_puppeteer.PuppeteerRequest(
'https://codesandbox.io/search?page=1',
wait_until='networkidle2',
)
def parse(self, response):
for selector_item in response.selector.xpath(
'//li[@class="ais-Hits-item"]'):
self.items.append(selector_item.xpath('.//h2').extract_first())
def setUp(self):
"""Store the Scrapy …Run Code Online (Sandbox Code Playgroud) 我尝试从代码战中完成任务。
的除数42是:1, 2, 3, 6, 7, 14, 21, 42。这些除数的平方是:1, 4, 9, 36, 49, 196, 441, 1764。除数平方的总和2500是50 * 50,一个平方!
鉴于两个整数m, n (1 <= m <= n)我们希望找到之间的所有整数m和n其平方除数的总和本身就是一个正方形。42是这样的数字。
结果将是一个数组数组,每个子数组有两个元素,首先是除数平方为平方的数字,然后是除数平方的和。
例子:
list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]]
list_squared(42, 250) --> [[42, 2500], [246, 84100]]
Run Code Online (Sandbox Code Playgroud)
以上是题主。
我的代码已经通过了所有测试,但是有一个错误Execution Timed Out,可能是我的代码没有优化。也许有人帮我优化我的代码。
这是我的代码
import math
def list_squared(m, n):
number = 0
result = []
if …Run Code Online (Sandbox Code Playgroud) 有什么方法可以将当前修订号存储在数据库中吗?我的意思是,当我生成迁移和升级头时,如何在数据库中插入此修订号,并在下次进行迁移时检查表中的此修订号。
我有一些元组列表:
a = [('3 232', 'm3', 'brutto'), ('1', 'm', 'netto_brutto_unknown'), ('90', 'cm3', 'netto_brutto_unknown')]
Run Code Online (Sandbox Code Playgroud)
我尝试按每个元组中的第一个元素对其进行排序:
sorted(a, key=lambda x: int(x.strip()[0]))
Run Code Online (Sandbox Code Playgroud)
但是我有AttributeError:
AttributeError:“ tuple”对象没有属性“ strip”
为什么这样做以及如何删除每个第一个元组元素中的空格?
我会很感激的
我有字典的字典:
a = {
'a': {'id': 1},
'b': {'id': 1},
'c': {'id': 1}
}
Run Code Online (Sandbox Code Playgroud)
和字典列表:
b = [{'word': 'foo'}, {'word': 'baz'}, {'word': 'bar'}]
Run Code Online (Sandbox Code Playgroud)
我需要将 a 中的每个字典更新为 b 中的每个值关键字
例子:
a = {
'a': {'id': 1, 'word': foo},
'b': {'id': 1, 'word': baz},
'c': {'id': 1, 'word': bar}
}
Run Code Online (Sandbox Code Playgroud)
我尝试用下一种方法来做:
[
a.update(
{
'word': i
}
)
for a in a.values()
for i in [
df['word'] for df in b
]
]
Run Code Online (Sandbox Code Playgroud)
但我有所有新键和最后一个词栏:
a = {
'a': {'id': 1, 'word': bar}, …Run Code Online (Sandbox Code Playgroud) 我有以下型号:
class Student(models.Model):
first_name = models.CharField(verbose_name='student first name', max_length=64)
last_name = models.CharField(verbose_name='student last name', max_length=64)
email = models.EmailField()
class Meta:
db_table = 'student'
def __str__(self):
return self.first_name + ' ' + self.last_name
class Course(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
start_date = models.DateField(null=True, blank=True, default=None)
end_date = models.DateField(null=True, blank=True, default=None)
class Meta:
db_table = 'course'
def __str__(self):
return self.name
class CourseParticipant(models.Model):
course = models.ForeignKey(Course, related_name='courses', on_delete=models.CASCADE)
student = models.ForeignKey(Student, related_name='student_name', on_delete=models.CASCADE)
completed = models.BooleanField(null=False, default=False)
class Meta:
db_table = 'course_participant' …Run Code Online (Sandbox Code Playgroud) 我有两个字典列表:
a = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}]
b = [{'id': 1, 'name': 'test'}, {'id': 2, 'name': 'test'}, {'id': 3, 'name': 'test'}, {'id': 4, 'name': 'test'}, {'id': 5, 'name': 'test'}]
Run Code Online (Sandbox Code Playgroud)
我需要使用by key的字典中的akey更新字典。我预期的结果:'name'b'id'
a = [{'id': 1, 'name': 'test'}, {'id': 2, 'name': 'test'}, {'id': 3, 'name': 'test'}, {'id': 4, 'name': 'test'}]
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
python ×9
sqlalchemy ×3
alembic ×2
algorithm ×1
asyncpg ×1
chromium ×1
dictionary ×1
django ×1
list ×1
postgresql ×1
puppeteer ×1
python-3.x ×1
scrapy ×1