小编Lin*_*yen的帖子

Sqlalchemy 包含带有 join 和 contains_eager 的空关系

我有 2 个模型 Recording 和 Recording_results 像这样

class Recording(Base):
    __tablename__ = 'recordings'

    id = Column(Integer, primary_key=True)
    filename = Column(String, nullable=False)

    language_id = Column(Integer, ForeignKey('languages.id'), nullable=False)
    language = relationship("Language", back_populates="recordings")

    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    user = relationship("User", back_populates="recordings")

    created_at = Column(DateTime, nullable=False, default=func.now())
    updated_at = Column(DateTime, nullable=False,
                        default=func.now(), onupdate=func.now())
    deletedd_at = Column(DateTime, nullable=True)

    def __repr__(self):
        return 'id: {}'.format(self.id)

User.recordings = relationship("Recording", order_by=Recording.id, back_populates="user")
Language.recordings = relationship("Recording", order_by=Recording.id, back_populates="language")


class RecordingResult(Base):
    __tablename__ = 'recording_results'

    id = Column(Integer, primary_key=True)
    is_with_dictionary = Column(Boolean, …
Run Code Online (Sandbox Code Playgroud)

python json sqlalchemy filter relationship

6
推荐指数
1
解决办法
1万
查看次数

找不到testing.postgresql命令:docker内的initdb

你好,我正在尝试使用 sqlalchemy 和 alembic 使用 postgresql 数据库进行单元测试

我也在 docker postgresql 上运行它

我按照testing.postgresql( docs )的文档设置一个临时的postgresql实例处理数据库测试并编写了以下测试:

def test_crawl_bds_obj(self):
    with testing.postgresql.Postgresql() as postgresql:
        engine.create_engine(postgresql.url())
        result = crawl_bds_obj(1 ,'/ban-can-ho-chung-cu-duong-mai-chi-tho-phuong-an-phu-prj-the-sun-avenue/nh-chu-gap-mat-tien-t-q2-thuoc-du-tphcm-pr22171626')
        self.assertEqual(result, 'sell')
Run Code Online (Sandbox Code Playgroud)

crawl_bds_obj() 基本上保存来自 URL 的信息,并使用 session.commit() 将其保存到数据库并返回类型数据

当我尝试运行测试时,它返回以下错误:

ERROR: test_crawl_bds_obj (tests.test_utils.TestUtils)
raise RuntimeError("command not found: %s" % name)
RuntimeError: command not found: initdb
Run Code Online (Sandbox Code Playgroud)

在文档中,它说“testing.postgresql.Postgresql 在实例化时执行 initdb 和 postgres。在删除 Postgresql 对象时,它会终止 PostgreSQL 实例并删除临时目录。”

那么,当我已经安装了testing.postgresql并且postgresql在我的docker上运行时,为什么我会收到initdb错误呢?

编辑:

我也设置了我的数据路径,但它仍然返回相同的错误

docker文件:

FROM python:slim-jessie
ADD requirements.txt /app/requirements.txt
ADD . /app/
WORKDIR /app/
RUN pip install -r requirements.txt
Run Code Online (Sandbox Code Playgroud)

docker-撰写:

  postgres:
    image: …
Run Code Online (Sandbox Code Playgroud)

python postgresql sqlalchemy docker python-unittest

6
推荐指数
1
解决办法
3755
查看次数

NodeJS 转换为字节数组代码与 python 相比返回不同的结果

我得到了以下 Javascript 代码,我需要将其转换为 Python(我不是哈希方面的专家,所以很抱歉我在这个主题上的知识)

function generateAuthHeader(dataToSign) {
    let apiSecretHash = new Buffer("Rbju7azu87qCTvZRWbtGqg==", 'base64');
    let apiSecret = apiSecretHash.toString('ascii');
    var hash = CryptoJS.HmacSHA256(dataToSign, apiSecret);
    return hash.toString(CryptoJS.enc.Base64);
}
Run Code Online (Sandbox Code Playgroud)

当我跑的时候generateAuthHeader("abc")它返回了+jgBeooUuFbhMirhh1KmQLQ8bV4EXjRorK3bR/oW37Q=

所以我尝试编写以下Python代码:

def generate_auth_header(data_to_sign):
    api_secret_hash = bytearray(base64.b64decode("Rbju7azu87qCTvZRWbtGqg=="))
    hash = hmac.new(api_secret_hash, data_to_sign.encode(), digestmod=hashlib.sha256).digest()
    return base64.b64encode(hash).decode()
Run Code Online (Sandbox Code Playgroud)

但是当我运行时generate_auth_header("abc")它返回了不同的结果aOGo1XCa5LgT1CIR8C1a10UARvw2sqyzWWemCJBJ1ww=

有人能告诉我我的 Python 代码有什么问题以及我需要更改什么吗?

base64 是我为这篇文章自己生成的字符串

更新:这是我正在使用的文档

//Converting the Rbju7azu87qCTvZRWbtGqg== (key) into byte array 
//Converting the data_to_sign into byte array 
//Generate the hmac signature
Run Code Online (Sandbox Code Playgroud)

它看起来像apiSecretHash并且api_secret_hash是不同的,但我不太明白,因为new Buffer()NodeJS 中的等价物bytearray()在 …

javascript python arrays hash node.js

6
推荐指数
1
解决办法
356
查看次数

谷歌云语音导入错误:无法导入名称“枚举”

我正在为我的项目使用 google-cloud-speech api。我在虚拟环境中使用 pipenv 我安装了 google-cloud-speech api

pipenv 安装 google-cloud-speech

pipenv 更新谷歌云语音

我跟着这个文档https://cloud.google.com/speech-to-text/docs/reference/libraries

这是我的代码:

谷歌.py:

# !/usr/bin/env python
# coding: utf-8
import argparse
import io
import sys
import codecs
import datetime
import locale
import os

from google.cloud import speech_v1 as speech
from google.cloud.speech import enums
from google.cloud.speech import types

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.join("alt_speech_dev_01-fa5fec6806d9.json")
def get_model_by_language_id(language_id):
    model = ''
    if language_id == 1:
        model = 'ja-JP'
    elif language_id == 2:
        model = 'en-US'
    elif language_id == 3:
        model = "zh-CN" …
Run Code Online (Sandbox Code Playgroud)

python import google-speech-api google-cloud-speech pipenv

5
推荐指数
2
解决办法
6833
查看次数

猫鼬更新数组对象中的字段

我正在使用 mongoose findOneAndUpdate() 在 mongodb 中,我有一个包含数组内对象的数据库,如下所示:

病人模型

{
        "_id" : ObjectId("5cb939a3ba1d7d693846136c"),
        "myArray" : [
            {
                "name" : "PW6178281935-20190425",
                "treatment" : "beauty",
                "value" : 0 <- i want to update this
            },
            {
                "name" : "PW6178281935-24142444",
                "treatment" : "muscle",
                "value" : 0
            }
        ] 
},
 {
        "_id" : ObjectId("5cc123a3bb2d3123a932475f"),
        "myArray" : [
            {
                "name" : "PW6178281935-43535555",
                "treatment" : "helps",
                "value" : 0 
            },
            {
                "name" : "PW6178281935-92732978",
                "treatment" : "documents",
                "value" : 0
            }
        ] 
}
Run Code Online (Sandbox Code Playgroud)

我想更新一个对象的值,处理 = "beauty" of _id …

mongoose mongodb node.js

4
推荐指数
1
解决办法
6336
查看次数

Django-rest-framework API 测试 403 {'detail': '您无权执行此操作。'}

我目前正在编写一个测试来测试我的获取请求,获取请求需要标头中的 jwt access_token,我使用 django-rest-framework-simplejwt 来获取令牌并将其用作默认身份验证类

设置.py:

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAdminUser',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    # 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}
Run Code Online (Sandbox Code Playgroud)

我的 test_api.py:

from rest_framework.test import APITestCase
from rest_framework import status
from rest_framework.test import APIClient 
from django.urls import reverse
from listing.models import Property
from backend.models import User

class PropertyTestCase(APITestCase):
    def setUp(self):
        property_1 = Property.objects.create(title="test", size=322.00, price=8000000, price_rent=300000, price_per_square_meter=500000, price_rent_per_square_meter=20000, description="description 1", type="sell", category="category 1", address="address 1", …
Run Code Online (Sandbox Code Playgroud)

python django jwt django-rest-framework django-tests

3
推荐指数
1
解决办法
4765
查看次数

数组中具有相同起始字符的Javascript组字

我目前正在研究javascript,并且在尝试弄清楚如何处理此问题时遇到问题:

我有这样的带有特殊问号的单词数组

wordsArray = [“为什么”,“会”,“您”,“付款”,“用于”,“一个”,“电话”,“?”];

我试图在数组的同一单独组中将具有相同起始字符的单词分组,示例输出将是:

firstArray = ["why", "would"] //<- all start with w
secondArray = ["you"]
thirdArray = ["pay", "phone"]//<- all start with p
fourthArray = ["for"]
fifthArray = ["a"] 
finalArray = ["?"]//<- special character like ?, :,.. in the same group
Run Code Online (Sandbox Code Playgroud)

我该如何实现?我写错了这个问题,看起来好像我在问代码,但是我实际上是在寻求解决方案,以解决这个问题(逻辑上)

javascript arrays grouping

1
推荐指数
1
解决办法
561
查看次数

Django get_model() 模型没有属性“objects”

我正在编写一个迁移来更新数据,我使用 get_model() 就像文档描述的那样来获取模型类,如下所示:

from django.db import migrations

def update_student(apps, schema_editor):
    # We can't import the model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    CourseClass = apps.get_model('backend', 'CourseClass')
    from pprint import pprint
    pprint(vars(CourseClass))
    for course_class in CourseClass.objects.all():
        if course_class.course:
            if course_class.course.student:
                course_class.students.add(course_class.course.student)
    
    Course = apps.get_model('backend', 'Course')
    for course in Course.objects.all():
        if course.student:
            course.students.add(course.student)

class Migration(migrations.Migration):

    dependencies = [
        ('backend', '0199_auto_20211027_1026'),
    ]

    operations = [
        migrations.RunPython(update_student, migrations.RunPython.noop)
    ]
Run Code Online (Sandbox Code Playgroud)

这是我的模型和一些自定义管理器:

class CourseClass(models.Model): …
Run Code Online (Sandbox Code Playgroud)

python django django-models

1
推荐指数
1
解决办法
1816
查看次数