繁体   English   中英

从 Python2.7 代码到 Python3 的 Python API 转换

[英]Python API conversion from Python2.7 code to Python3

我正在尝试将这部分转换为 Python3,但无法使其正常工作。

import urllib
import datetime
import urllib2
import httplib
import hmac
from hashlib import sha256

TIMEOUT=60

def getDimMetrics(options):
    now = datetime.datetime.now()
    
    # create a dictionary of the arguments to the API call
    post_dict = {}
    
    if options.group:
        post_dict['group'] = options.group
        
        # start and end are dates, the format will be specified on the command line
        # we will simply pass those along in the API
        
    if options.start:
        post_dict['start'] = options.start
        
    if options.end:
        post_dict['end'] = options.end
        
        # encode the data
        post_data = urllib.urlencode(post_dict)
        protocol = 'https'
        
    if 'localhost' in options.host:
        # for testing
        protocol = 'http'
        url = protocol + '://' + options.host + options.url + '.' + options.type.lower()
        
        # create the request
        request = urllib2.Request(url, post_data)
        
        # add a date header (optional)
        request.add_header('Date', str(now))

        # calculate the authorization header and add it
        hashString = 'POST' + request.get_selector() + request.get_header('Date') + 'application/x-www-form-urlencoded' + str(len(request.get_data()))
        calc_sig = hmac.new(str(options.secret), hashString,
        sha256).hexdigest()
        request.add_header('Authorization', 'Dimo %s:%s' %(options.key, calc_sig))

        print 'url=', url
        print 'post_data=', post_data
        print 'headers=', request.headers

这就是我在 Python3 中所拥有的。 当我运行它时,我收到一条错误消息,指出 400 Malformed Authorization 标头。 如何修复此错误,以便我可以在 python 3 中运行这部分。

from requests_oauthlib import OAuth1Session

CONSUMER_KEY = "aaaaaaaaaaaaaaaaa"
CONSUMER_SECRET = "bbbbbbbbbbbbbbbbbbbb"
host = "api.dimo.com"
uri = "/api/Visits.json"

oauthRequest = OAuth1Session(CONSUMER_KEY,
                    client_secret=CONSUMER_SECRET)

url = 'https://' + host + uri

headers = {
        'Accept': "application/json",
        'Accept-Encoding': "application/x-www-form-urlencoded",
        'Authorization': "dimo bbbbbbbbbbbbbbb"
    }

response = oauthRequest.post(url, headers=headers)

print(response.status_code)
print(response.content)

错误400 b'格式错误的授权标头。\\n'

问题

  1. 您在将 python 2.7 代码转换为 python 3.x 时遇到问题。
  2. 原始 python 3 转换代码中的授权标头无效。

解决方案

运行 python 2to3转换器,并根据PEP 8 - Python 样式指南( 最大行长度等)进行一些额外的清理。

例子

import datetime
import urllib.request
import urllib.error
import urllib.parse
import http.client
import hmac
from hashlib import sha256

TIMEOUT = 60


def getDimMetrics(options):
    now = datetime.datetime.now()

    # create a dictionary of the arguments to the API call
    post_dict = {}

    if options.group:
        post_dict['group'] = options.group

    # start and end are dates, the format will be specified on the command line
    # we will simply pass those along in the API
    if options.start:
        post_dict['start'] = options.start

    if options.end:
        post_dict['end'] = options.end

        # encode the data
        post_data = urllib.parse.urlencode(post_dict)
        protocol = 'https'

    if 'localhost' in options.host:
        # for testing
        protocol = 'http'
        url = f'{protocol}://{options.host}{options.url}.' \
              f'{options.type.lower()}'

        # create the request
        request = urllib.request.Request(url, post_data)

        # add a date header (optional)
        request.add_header('Date', str(now))

        # calculate the authorization header and add it
        hashString = f'POST{request.get_selector()}' \
                     f'{request.get_header('Date')}' \
                     f'application/x-www-form-urlencoded' \
                     f'{str(len(request.get_data()))}'

        calc_sig = hmac.new(
            str(options.secret), hashString, sha256).hexdigest()
        request.add_header('Authorization', 'Dimo {options.key}:{calc_sig}')

        print(f'url={url}')
        print(f'post_data={post_data}')
        print(f'headers={request.headers}')

参考

Python 2to3: https : //docs.python.org/3/library/2to3.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM