小编Kur*_*eek的帖子

如何设置Postgres扩展?

在最新版本的Django(1.8)中,添加了一些模型字段以利用Postgres数据类型.我对HStoreField感兴趣并且文档要求设置PG 扩展以便HStoreField在模型中使用新的s.

我如何实际使用此类HStoreExtension来执行数据库扩展?

python django postgresql

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

在日志模块的 RotatingFileHandler 中,如何将 backupCount 设置为几乎无限的数字

我正在编写一个使用 Python 的RotatingFileHandler备份数据库的程序。这有两个参数,maxBytes和backupCount:前者是每个日志文件的最大大小,后者是日志文件的最大数量。

我想实际上永远不会删除数据,但每个日志文件仍然具有一定的大小(例如,出于说明目的,为 2 kB)。所以我尝试将backupCount参数设置为sys.maxint:

import msgpack
import json
from faker import Faker
import logging
from logging.handlers import RotatingFileHandler
import os, glob
import itertools
import sys

fake = Faker()
fake.seed(0)

data_file = "my_log.log"

logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
handler = RotatingFileHandler(data_file, maxBytes=2000, backupCount=sys.maxint)
logger.addHandler(handler)

fake_dicts = [{'name': fake.name(), 'email': fake.email()} for _ in range(100)]

def dump(item, mode='json'):
    if mode == 'json':
        return json.dumps(item)
    elif mode == 'msgpack':
        return msgpack.packb(item)

mode …
Run Code Online (Sandbox Code Playgroud)

python

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

"gaierror:[Errno -3]名称解析暂时失败"是什么意思

我正在尝试运行一个以错误结束的Flask应用程序.如果我追溯发生的事情,我可以使用以下iPython命令重现该问题:

In [14]: import socket

In [15]: s = socket.socket()

In [16]: s.connect(('rabbitmq', 5672))
---------------------------------------------------------------------------
gaierror                                  Traceback (most recent call last)
<ipython-input-16-71a261d976b3> in <module>()
----> 1 s.connect(('rabbitmq', 5672))

/usr/lib/python2.7/socket.pyc in meth(name, self, *args)
    226 
    227 def meth(name,self,*args):
--> 228     return getattr(self._sock,name)(*args)
    229 
    230 for _m in _socketmethods:

gaierror: [Errno -3] Temporary failure in name resolution
Run Code Online (Sandbox Code Playgroud)

我无法找到关于"名称解析暂时失败"的根本原因的大量文档.问题的一个可能原因是我试图在本地运行应用程序,而它通常在docker-compose环境中初始化.是什么原因造成了这个错误?

python sockets

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

如何使用无限循环的目标函数创建一个可停止的线程

假设我想run_forever()在一个线程中运行一个名为的函数,但仍然可以通过按Ctrl+ 来"停止" C.我已经看到了使用StoppableThread子类的方法threading.Thread,但这些似乎涉及将目标函数"复制"到该子类中.我想保持功能"它在哪里".

请考虑以下示例:

import time
import threading

def run_forever():  # An externally defined function which runs indefinitely
    while True:
        print("Hello, world!")
        time.sleep(1)

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self, *args, **kwargs):
        super(StoppableThread, self).__init__(*args, **kwargs)
        self._stop = threading.Event()

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()

    def run(self):
        while not self.stopped():
            run_forever()             # This doesn't work
            # print("Hello, …
Run Code Online (Sandbox Code Playgroud)

python python-multithreading

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

尝试遵循Python Elasticsearch示例用法的“连接被拒绝”错误

我正在尝试为Python Elasticsearch运行'示例用法'脚本:

from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()

doc = {
    'author': 'kimchy',
    'text': 'Elasticsearch: cool. bonsai cool.',
    'timestamp': datetime.now(),
}
res = es.index(index="test-index", doc_type='tweet', id=1, body=doc)
print(res['created'])

res = es.get(index="test-index", doc_type='tweet', id=1)
print(res['_source'])

es.indices.refresh(index="test-index")

res = es.search(index="test-index", body={"query": {"match_all": {}}})
print("Got %d Hits:" % res['hits']['total'])
for hit in res['hits']['hits']:
    print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])
Run Code Online (Sandbox Code Playgroud)

但是,出现以下错误:

Traceback (most recent call last):
  File "elasticsearch_example_usage.py", line 10, in <module>
    res = es.index(index="test-index", doc_type='tweet', id=1, body=doc) …
Run Code Online (Sandbox Code Playgroud)

python elasticsearch

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

在ipdb中,如何查询与命令同名的变量?

我正在尝试调试一个quicksort(A, l, r)具有名为 的局部变量的函数l。然而,在 ipdb 中,它也对应于查看当前行周围代码的命令。所以我看到这样的事情:

ipdb> dir()
['A', 'ipdb', 'l', 'r']
ipdb> A
[2, 4, 6, 1, 3, 5, 7, 8]
ipdb> l
     14         A[0], A[p] = A[p], A[0]
     15 
     16 def quicksort(A, l, r):
     17         # n = len(A)
     18         import ipdb; ipdb.set_trace()
---> 19         if len(A) == 1:
     20                 return
     21         else:
     22                 # choose_pivot(A)
     23                 q = partition(A, l, r)
     24                 quicksort(A, l, q-1)
Run Code Online (Sandbox Code Playgroud)

然而,在这种情况下,我实际上想做的是查看 的值l。有没有办法“转义”默认l命令并查看变量的值l?

python ipdb

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

Django 编程错误:在 Django 源代码中创建迁移后关系已存在?

我最近检查了一个项目的主分支,有一些模型更改尚未反映在迁移中:

(venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auditlog, auth, contenttypes, lucy_web, oauth2_provider, otp_static, otp_totp, sessions, two_factor
Running migrations:
  No migrations to apply.
  Your models have changes that are not yet reflected in a migration, and so won't be applied.
  Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
Run Code Online (Sandbox Code Playgroud)

按照说明,我跑去makemigrations创建它们:

(venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py makemigrations
Migrations for 'auth':
  venv/lib/python3.6/site-packages/django/contrib/auth/migrations/0009_auto_20180425_1129.py
    - Alter field email on user …
Run Code Online (Sandbox Code Playgroud)

python django

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

CircleCI 没有选择运行步骤中定义的环境变量?

我试图运行一个Django项目,其中CircleCI测试manage.py确定的版本settings.py适用(development.py,staging.py或production.py从一个环境变量)ENV_ROLE。以前,如果未定义,ENV_ROLE则设置为默认值development,但我正在更改它,以便 DjangoImproperlyConfigured在未定义时抛出错误。

为了使测试通过,我需要ENV_ROLE在我们的 CircleCI 测试环境中定义环境变量。在https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-step之后,我在run步骤中添加了以下内容:

      - run:
          environment:
            ENV_ROLE: development
Run Code Online (Sandbox Code Playgroud)

但是,我仍然从 CircleCI 收到此错误:

#!/bin/bash -eo pipefail
cd lucy-web
source venv/bin/activate
python manage.py compilescss --verbosity 0
python manage.py collectstatic --clear --no-input --verbosity 0
flake8
python manage.py test
Traceback (most recent call last):
  File "/root/lucy/lucy_web/lucy-web/env.py", line 5, in <module>
    ENV_ROLE = os.environ['ENV_ROLE']
  File "/usr/local/lib/python3.6/os.py", line 669, in __getitem__ …
Run Code Online (Sandbox Code Playgroud)

python django yaml circleci

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

尽管两个查询集在 shell 中打印出相同的结果,Django 的 assertQuerysetEqual() 方法还是失败了?

我有一个Family和一个Session一对多的关系,这样一个实例family有一个session_set. 此外,Session还有一个session_number字段,它是一个整数。

我有两个Family,family1和 的实例family2,这样如果我session_set.order_by('session_number')在ipdb调试器中打印出它们,我就会发现它们看起来完全一样:

ipdb> family1.session_set.order_by('session_number')
<QuerySet [<Session: Welcome>, <Session: First-Time Parents: The Basics of Birth>, <Session: Initial Postpartum Lactation>, <Session: Sleep Techniques for New Babies>, <Session: Breastfeeding Preparation>, <Session: Newborn Care Basics>, <Session: Easing the Transition Back to Work>, <Session: Preparing for Parenting>, <Session: Decoding Baby Cues>, <Session: Postpartum Doula Support>, <Session: First-Time Parents: Birth Prep Q&A>, …
Run Code Online (Sandbox Code Playgroud)

python django django-testing

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

尝试在 create-react-app 中使用 dotenv 时出现“未捕获的引用错误:进程未定义”

在存储库https://github.com/khpeek/trailmaps中,我有一个创建的 Google 地图示例,react-google-maps其中googleMapUrlprop 包含我的 Google 地图 API 密钥。根据 12 因素原则,我想将此 API 密钥移至.env文件中并将其插入 URL 中。

我正在尝试遵循该模块的说明dotenv(与 一起提供create-react-app),并尝试了以下操作:

import React, { Component } from 'react';
import './App.css';
import MapWithGroundOverlay from './components/groundOverlay';
require('dotenv').config()

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Custom Overlay</h1>
          <h1 className="App-title">{`The API key is ${process.env.GOOGLE_MAPS_API_KEY}`}</h1>

        </header>
        <MapWithGroundOverlay
          googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyBimnrhiugaGSNN8WnsjpzMNJcrH_T60GI&v=3.exp&libraries=geometry,drawing,places"
          loadingElement={<div style={{ height: `100%` }} />}
          containerElement={<div style={{ height: `400px` }} />}
          mapElement={<div …
Run Code Online (Sandbox Code Playgroud)

javascript environment-variables reactjs

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