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

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 header。我怎样才能修复这个错误,以便我可以在 python 3.

中得到这部分 运行ning
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'格式错误的授权 header。\n'

问题

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

解决方案

运行 python 2to3 converter with some additional cleanup based on PEP 8 -- Style Guide for Python ( max line length, 等等).

示例

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