小编Hus*_*ain的帖子

Flask-restful API授权.访问装饰器内的current_identity

我使用flask-restful来创建我的API.我用于flask-jwt启用基于身份验证JWT.现在我需要做授权.

我试过把我的授权装饰器.

test.py(/ test api)

from flask_restful import Resource
from flask_jwt import jwt_required

from authorization_helper import authorized_api_user_type


class Test(Resource):

    decorators = [jwt_required(), authorized_api_user_type()]

    def get(self):
        return 'GET OK'

    def post(self):
        return 'POST OK'
Run Code Online (Sandbox Code Playgroud)

基本上为了处理基本授权,我需要访问current_identity并检查它的类型.然后基于它的类型我将决定用户是否有权访问api/resources.

current_identity似乎是empty那个装饰者.因此,要间接获取它,我必须看到代码jwt_handler并在那里完成工作.

authorization_helper.py

from functools import wraps
from flask_jwt import _jwt, JWTError
import jwt
from models import Teacher, Student

def authorized_api_user_type(realm=None, user_type='teacher'):
    def wrapper(fn):
        @wraps(fn)
        def decorator(*args, **kwargs):
            token = _jwt.request_callback()

            if token is None: …
Run Code Online (Sandbox Code Playgroud)

python flask flask-restful flask-jwt

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

如何在PHP中的celery-rabbitmq队列上发布任务?

我安装了以下版本的芹菜和rabbitmq -

芹菜3.1.6
rabbitmq 3.1.1

我可以从PHP发布任务到默认队列 -

//client.php
<?php
require 'celery-php/celery.php';
$c = new Celery('localhost', 'guest', 'guest', '/');
$result = $c->PostTask('tasks.add', array(2,2));
Run Code Online (Sandbox Code Playgroud)

我的worker模块是python -

# tasks.py
from celery import Celery
celery = Celery('tasks', broker='amqp://guest:guest@localhost:5672//')
@celery.task(queue='demo', name='add')
def add(x, y):
    return x + y
Run Code Online (Sandbox Code Playgroud)

我像这样经营芹菜工人和客户 -

# terminal window 1
$ celery -A tasks worker --loglevel=info
# terminal window 2
$ php -f client.php
Run Code Online (Sandbox Code Playgroud)

这有效.我在终端窗口1中看到下面的输出:

Received task: tasks.add[php_52b1759141a8b3.43107845]
Task tasks.add[php_52b1759141a8b3.43107845] succeeded in 0.000701383920386s: 4
Run Code Online (Sandbox Code Playgroud)

但我希望有不同的队列.对于演示,假设我只想要一个名为demo的队列.所以我像这样经营我的芹菜工人 -

$ celery -A …
Run Code Online (Sandbox Code Playgroud)

php python rabbitmq celery

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

如何在具有Ubuntu 12.04的32位机器上安装Docker?

我已经按照docker安装文档将它安装在我的机器上,这是一台运行Ubuntu 12.04的32位机器

这一步

$ sudo apt-get install docker-engine
Run Code Online (Sandbox Code Playgroud)

没说

E: Unable to locate package docker-engine
Run Code Online (Sandbox Code Playgroud)

应该已经安装好了吧?

我也知道,Docker目前只支持64位平台.

$ wget -qO- https://get.docker.io/ | sh
Error: you are not using a 64bit platform.
Docker currently only supports 64bit platforms.
Run Code Online (Sandbox Code Playgroud)

有没有办法安装它并使其在32位机器上工作?

32-bit ubuntu-12.04 docker

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

我应该如何在python中解析这个xml字符串?

我的XML字符串是 -

xmlData = """<SMSResponse xmlns="http://example.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
             <Cancelled>false</Cancelled>
             <MessageID>00000000-0000-0000-0000-000000000000</MessageID>  
             <Queued>false</Queued>
             <SMSError>NoError</SMSError>
             <SMSIncomingMessages i:nil="true"/>
             <Sent>false</Sent>
             <SentDateTime>0001-01-01T00:00:00</SentDateTime>
             </SMSResponse>"""
Run Code Online (Sandbox Code Playgroud)

我试图解析并获取标签的值 - Canceled,MessageId,SMSError等.我正在使用python的Elementtree库.到目前为止,我尝试过像 -

root = ET.fromstring(xmlData)
print root.find('Sent')  // gives None
for child in root:
    print chil.find('MessageId') // also gives None
Run Code Online (Sandbox Code Playgroud)

虽然,我能够用 - 打印标签 -

for child in root:
    print child.tag
    //child.tag for the tag Cancelled is - {http://example.com}Cancelled
Run Code Online (Sandbox Code Playgroud)

和他们各自的价值 -

for child in root:
    print child.text
Run Code Online (Sandbox Code Playgroud)

我如何获得类似的东西 -

print child.Queued // will print false
Run Code Online (Sandbox Code Playgroud)

就像在PHP中一样,我们可以使用root访问它们 -

$xml = simplexml_load_string($data);
$status …
Run Code Online (Sandbox Code Playgroud)

python xml elementtree

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

使用 APIRequestFactory 对 Django 的 rest api 进行单元测试时无法获取 url 参数

我使用 Django 的rest_framework. 它是使用基于类的视图创建的。

视图.py

import logging
from rest_framework.views import APIView
from rest_framework.authentication import BasicAuthentication, SessionAuthentication, TokenAuthentication
from rest_framework.response import Response

from handlers.product import get_data

log = logging.getLogger(__name__)

class ProductView(APIView):
    authentication_classes = (TokenAuthentication, BasicAuthentication, SessionAuthentication)

    def get(self, request, **kwargs):
        try:
            product_id = kwargs['product_id']
            response = get_data(product_id)
            return Response(response)
        except KeyError as key:
            log.exception(key)
            return Response({'error_msg': '{} is required'.format(key)}, status=400)
Run Code Online (Sandbox Code Playgroud)

网址.py

url(r'^product/(?P<product_id>[0-9]+)/data/$', ProductView.as_view(), name='product'),
Run Code Online (Sandbox Code Playgroud)

这就是我尝试过的,

import pytest
from django.contrib.auth.models import User
from mixer.backend.django import mixer
from rest_framework.authtoken.models import Token …
Run Code Online (Sandbox Code Playgroud)

python django rest

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

从developer.sandbox.com模拟IPR for recurring_payment_skipped

我需要在定期付款失败时模拟IPN.然后,我的应用程序可以创建创建待定发票并将其发送给客户.

我搜索并发现我需要设置将在下面处理的IPN txn_type

  • recurring_payment_skipped
  • recurring_payment_failed

这两个是否足够?

最近 提供了一个名为IPN Simulator的新工具,您可以在其中将示例IPN发送到URL.它只支持txn_types 以下

  • web_accept (eCheck-pending,eCheck-rejected,eCheck-complete)
  • cart (快速结账,购物车结账)
  • web_accept (Web接受,退款)

    等等.但没有recurring_payment_skippedrecurring_payment_failed

我在哪里可以模拟出来的?

请帮帮我.

paypal paypal-subscriptions paypal-ipn

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

无法使用Python的mock.patch来模拟urllib2.urlopen

下面是我的api.py模块的代码片段

# -*- coding: utf-8 -*-

from urllib2 import urlopen
from urllib2 import Request

class API:

    def call_api(self, url, post_data=None, header=None):
        is_post_request = True if (post_data and header) else False
        response = None
        try:
            if is_post_request:
                url = Request(url = url, data = post_data, headers = header)
            # Calling api
            api_response = urlopen(url)
            response = api_response.read()
        except Exception as err:
            response = err

        return response
Run Code Online (Sandbox Code Playgroud)

我试图嘲弄urllib2.urlopenunittest上述模块.我已经写了

# -*- coding: utf-8 -*-
# test_api.py

from unittest import …
Run Code Online (Sandbox Code Playgroud)

python unit-testing urllib2 python-mock

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

使用Gimp而不是我的Python代码手动预处理Image时,使用Tesseract-OCR进行文本识别的图像更好

我正在尝试用Python编写代码,用于使用Tesseract-OCR进行手动图像预处理和识别.

手动过程:
为了手动识别单个图像的文本,我使用Gimp预处理图像并创建TIF图像.然后我将它喂给Tesseract-OCR,它正确识别它.

使用Gimp预处理图像我做 -

  1. 将模式更改为RGB /灰度
    菜单 - 图像 - 模式 - RGB
  2. 阈值
    菜单 - 工具 - 颜色工具 - 阈值 - 自动
  3. 将模式更改为索引
    菜单 - 图像 - 模式 - 索引
  4. 调整大小/缩放到宽度> 300px
    菜单 - 图像 - 缩放图像 - 宽度= 300
  5. 保存为Tif

然后我喂它tesseract -

$ tesseract captcha.tif output -psm 6
Run Code Online (Sandbox Code Playgroud)

而且我一直都能得到准确的结果.

Python代码:
我试图使用OpenCV和Tesseract复制上述过程 -

def binarize_image_using_opencv(captcha_path, binary_image_path='input-black-n-white.jpg'):
    im_gray = cv2.imread(captcha_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
    (thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    # although thresh is used below, gonna pick something …
Run Code Online (Sandbox Code Playgroud)

python opencv tesseract image python-tesseract

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

PHP命令行错误:时区数据库已损坏

我的date.php是 -

<?php
echo date('Y');
Run Code Online (Sandbox Code Playgroud)

当我php -f date.php在我的登台机器上执行时,我收到错误 -

PHP Fatal error:  date(): Timezone database is corrupt - this should *never* happen! 
in /home/staging/test/date.php on line 2
Run Code Online (Sandbox Code Playgroud)

但是当我在我的本地/ dev机器上执行相同的工作时.虽然在登台和本地计算机上,权限/etc/localtime/usr/share/zoneinfo/是相同的.

file /etc/localtime两台机器的产量各不相同.

本地(php5.3.5):

/etc/localtime: timezone data, version 2, 4 gmt time flags, 4 std time flags, no leap seconds, 4 transition times, 4 abbreviation chars
Run Code Online (Sandbox Code Playgroud)

暂存(php5.3.10):

/etc/localtime: timezone data, version 2, 1 gmt time flag, 1 std time flag, no leap …
Run Code Online (Sandbox Code Playgroud)

php permissions timezone date

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

如何跟踪芹菜的重试

在芹菜中,我如何跟踪当前的重试?我知道我可以这样做:

@app.task(bind=True, default_retry_delay=900, max_retries=5)
def send_email(self, sender=None, to=None, subject=None, message=None):
  try:
    # Send email
  except Exception as e:
    # Print log message with current retry
    self.retry(e)
Run Code Online (Sandbox Code Playgroud)

但我想说这是尝试1/5..2/5等等.

python celery

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