小编Bri*_*ach的帖子

Python应用程序配置最佳实践

我知道之前已经讨论过这个问题,但我很难找到如何在本地开发和生产服务器之间进行配置的明星解释.

到目前为止我做了什么:我有一个my_app_config.py文件,其中有一个部分包含机器/场景(测试与生产)部分我可以注释掉.我将使用我的本地机器路径硬编码,测试数据库连接字符串,我的测试电子表格位置等.当需要将代码部署到服务器时,我注释掉"测试"部分并取消注释"生产部分".正如你可能猜到的那样,这是错误的.

我最近采用了Python ConfigParser库来使用.ini文件.现在,我的代码中有以下几行

import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'settings',
                                                     'my_app_config.ini')))
database_connect_string_admin = config.get('Database', 'admin_str')
Run Code Online (Sandbox Code Playgroud)

这个问题很多......

  1. 我需要在每个文件的顶部进行导入
  2. 文件名my_app_config.ini不能改变.所以,我依赖文件内容中的注释.ini来知道我正在处理哪一个.它们存储在文件夹树中,所以我知道哪个是哪个.
  3. 注意这里定义了配置文件的路径.因此,根据python文件在树结构中的位置,决定了我是否收到了复制/粘贴错误.

我尝试在程序开头设置环境变量,但所有模块的所有导入都会在代码启动时立即执行.我左右都有"未找到"的错误.

我想要的:了解如何将所有配置保存在一个不容易忘记我正在做的事情的地方.我想要一个简单的方法来保持这些配置文件(理想情况下是一个文件或脚本)在版本控制下(安全性是另一个问题,我离题).我希望能够无缝切换上下文(本地测试,本地生产,服务器测试,服务器生产,服务器B测试,服务器B生产)我的应用程序使用

  1. my_app_config.ini 由我的解析器读取
  2. uwsgi.ini 由uwsgi应用服务器皇帝读取
  3. web_config.py 烧瓶应用使用
  4. nginx.conf 符号链接到Web服务器的配置
  5. celery 组态

更不用说一切的不同路径(理想情况下在魔法配置处理精灵中处理).我想,一旦我想到这一点,我会感到很尴尬,需要很长时间才能掌握.

环境变量是我在这里尝试做的吗?

python configuration ini flask

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

忽略 Service Worker 请求中的查询参数

我正在尝试使用服务人员构建离线应用程序。我有一个资源列表,定义如下

var urlsToPrefetch = ['foo.html', 'bar.js']

查询字符串被添加到许多 URL 中,这导致服务工作人员的fetch事件失败,因为请求与缓存中定义的内容不匹配。查询字符串主要用于强制获取新文件版本。例如,bar.js要求为bar.js?version=2

有一个选项可以忽略查询字符串(ignoreSearch如下),尽管从 Chrome V50 开始尚未实现。Chrome Canary 仅适用于 Win/Mac

下面的代码位于fetch eventListener

event.respondWith(
    // caches.match() will look for a cache entry in all of the caches available to the service worker.
    // It's an alternative to first opening a specific named cache and then matching on that.

    caches.match(event.request, {'ignoreSearch': true} ).then(function(response) {
        if (response) {

            return response;
        }

        ...
)
Run Code Online (Sandbox Code Playgroud)

javascript service-worker

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

ngFor和*ngFor有什么区别

我无法在任何地方找到差异的良好描述.与*ngIf和相同ngIf

一个例子 *ngFor

<li *ngFor="let video of page" ...>
  <img src="api/Videos/{{video.id}}/thumbnail">
</li>
Run Code Online (Sandbox Code Playgroud)

和一个例子 ngFor

<template ngFor let-labelid [ngForOf]="labelLookup | keyValueFilter" >
  <label  [ngStyle]="{'background-color': labelLookup[labelid].color}">
    <input (click)="changeLabel(labelid)" type="radio" name="labelSelector" value="{{ labelid }}" [checked]="labelid == 1">
  </label>
</template>
Run Code Online (Sandbox Code Playgroud)

typescript angular

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

GCP CRON 作业失败且没有日志

我正在尝试在 Google Cloud Platform 中设置 CRON 作业。该作业显示在 GCP 控制台中,但它失败了。没有日志可以说明它失败的原因。计划似乎工作正常,我能够手动运行该作业,尽管手动启动时它也会失败。

如果我转到http://...../api/status/additurl 栏中,该作业将按预期运行。

任务队列页面上有一个“查看日志”的链接,它显示了我的 CRON 作业,但是当我转到这些日志时,它们完全是空的。

查看 nginx 请求日志不会显示对该 url 发出的任何请求(或任何与此相关的请求)。如果我手动转到作业的 url,我可以看到这些请求显示在日志中,并且应该发生的一切都发生了,所以我知道端点是好的。

Google App Engine 柔性环境,Python 3

烧瓶API

我还能提供哪些其他信息?有很多活动部分,我不想用不相关的信息淹没这个问题。

cron.yaml:

cron:
- description: 'test cron job'
  url: /api/status/addit
  schedule: every 1 minutes
Run Code Online (Sandbox Code Playgroud)

端点:

< some Flask Blueprint stuff initiates the "status" blueprint so that this url will resolve to /api/status/addit >
...

@status.route('/addit')
def add_to_file():
    print('made it into the request')
    from flask import Response
    res = Response("{'foo':'bar'}", status=202, mimetype='application/json')
    return …
Run Code Online (Sandbox Code Playgroud)

google-app-engine app-engine-flexible

6
推荐指数
2
解决办法
1556
查看次数

zip 文件内容未显示在 Windows 机器上(Python 的 zipfile 模块)

我正在将一些 csv 压缩成一个 zip 文件,以便从我的 Web 应用程序中通过电子邮件发送出去。

celery运行此任务并负责发送电子邮件。结构描述如下

import zipfile
...

def email_performance_report(performance_dict)
    zippath = performance_dict['folderpath'] + '.zip'
    ziph = zipfile.ZipFile(zippath, 'w')

    for root, dirs, files in os.walk(performance_dict['folderpath']):
        for file in files:
            filename = os.path.join(root, file)
            archivename = os.path.dirname(filename).split('/')[-1]
            filename_short = filename.split('/')[-1]
            ziph.write(filename, os.path.join(archivename, filename_short))

    ziph.close()

    ''' attach attachment '''
    with open(zippath, 'rb') as f:
        attachment = MIMEText(f.read())
    clean_attachment_name = zippath.split('/')[-1].split('|__|')[0] + '.zip'
    attachment.add_header('Content-Disposition', 'attachment', filename=clean_attachment_name)
    msg.attach(attachment)

    try:
            mailserver.sendmail(os.environ['MAIL_SENDER'], performance_dict['email_to'], msg.as_string())
    except smtplib.SMTPDataError:
        sqllogger.critical('A emailing of the report failed …
Run Code Online (Sandbox Code Playgroud)

python zip email-attachments

5
推荐指数
0
解决办法
273
查看次数

python数字字符串比较

我有从JSON对象加载的数值,因此都是字符串。

我在与这些字符串进行数值比较时遇到问题。以下对我来说毫无意义,我希望你们中的一位冠军能解释一下..

In[2]: print '100' < '45'
True

In[3]: print '99' < '45'
False
Run Code Online (Sandbox Code Playgroud)

使用 Python 2.7

python string comparison types

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

python pip install mod_wsgi失败,可能出现unicode错误

我正在尝试使用Flask托管一个Web应用程序.我有运行CentOS的VPS.我安装了Apache 2.2.26.

当我pip install mod_wsgi在虚拟环境中运行或在我的主Python安装上运行时,我会收到以下错误

在Python跟踪之前打印第一个错误...

/usr/bin/ld: /home5/arguably/python27/lib/python2.7/config/libpython2.7.a(abstra     ct.o): relocation R_X86_64_32 against `.rodata.str1.8' can not be used when maki     ng a shared object; recompile with -fPIC

/home5/arguably/python27/lib/python2.7/config/libpython2.7.a: could not read sym     bols: Bad value

collect2: ld returned 1 exit status

error: command 'gcc' failed with exit status 1
Run Code Online (Sandbox Code Playgroud)

该错误正在查看我的主要Python安装.这不是virtualenv所在的位置

Python错误......

Traceback (most recent call last):
  File "/home/arguably/webapps/ers_2/ers2venv/bin/pip", line 11, in <module>
    sys.exit(main())
  File "/home/arguably/webapps/ers_2/ers2venv/lib/python2.7/site-packages/pip/__     init__.py", line 185, in main
    return command.main(cmd_args)
  File "/home/arguably/webapps/ers_2/ers2venv/lib/python2.7/site-packages/pip/ba     secommand.py", line 161, in main …
Run Code Online (Sandbox Code Playgroud)

python apache mod-wsgi

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

如何从IDE停止跟踪git中的文件夹/文件

我使用PyCharm作为我的IDE,我喜欢它。我git用作我的版本控制系统。我在PyCharm中使用它(我不知道如何以其他任何方式有效地使用它)。偶尔,我将要停止跟踪中的文件git。无论我只是不想再跟踪它,还是.xml以某种方式将某些文件添加到git列表中,该文件总是会变化。

是真的没有停止跟踪git中文件或文件夹的方法吗?我发现的方法似乎花费了太多时间来做我认为应该很简单的事情?

我一直要做的第一件事是将它们添加到.gitignore文件中,但是事实并非如此。

git pycharm

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

具有声明属性的SQLAlchemy邻接表关系

我有一个由不同类型的子代继承的顶级模型声明

class HasId(object):

    @declared_attr
    def id(cls):
        return Column('id', Integer, Sequence('test_id_seq'), primary_key=True)
    ...
    @declared_attr
        def triggered_by_id(cls):
            return Column(Integer, ForeignKey('tests.id'), nullable=True)

    @declared_attr
        def triggered(cls):
            return relationship('TestParent',
                                foreign_keys='TestParent.triggered_by_id',
                                lazy='joined',
                                cascade='save-update, merge, delete, delete-orphan',
                                backref=backref('triggered_by', remote_side=[id])
                                )


class TestParent(HasId, Model):
    __tablename__ = 'tests'

    discriminator = Column(String(50))

    __mapper_args__ = {'polymorphic_on': discriminator}


class FooTest(TestParent):
    __tablename__ = 'footests'
    __mapper_args__ = {'polymorphic_identity': 'footests'}
    id = Column(Integer, ForeignKey('tests.id'), primary_key=True)

    bar = Column(Boolean)
    ...
Run Code Online (Sandbox Code Playgroud)

当IO尝试构建此数据库时,我收到一个错误,该错误是由于我remote_sidebackrefon triggered_by关系的定义所引起的。

完整的错误是

ArgumentError: Column-based expression object expected for argument 'remote_side'; …
Run Code Online (Sandbox Code Playgroud)

python sqlalchemy

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

排除连接表中没有关联行的行

我想获取表foo中没有引用的实例(行)bar

foo

+----+-----+
| id | baz |
+----+-----+
|  1 |  23 |
|  2 |  56 |
|  3 |  45 |
|  4 |  78 |
+----+-----+
Run Code Online (Sandbox Code Playgroud)

bar

+-----+--------+-----+
| id  | foo_id | zab |
+-----+--------+-----+
|  7  |      2 | s1  |
|  8  |      4 | s2  |
+-----+--------+-----+
Run Code Online (Sandbox Code Playgroud)

我的查询结果应该是以下实例foo

+----+-----+
| id | baz |
+----+-----+
|  1 |  23 |
|  3 | …
Run Code Online (Sandbox Code Playgroud)

python sqlalchemy

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