K
K
Kirill Morozov2017-07-17 18:31:57
MySQL
Kirill Morozov, 2017-07-17 18:31:57

How to rewrite code that works in Python 2.7 so that it works in version 3.6?

Please help me rewrite the code or point out the key points. The code works fine on version 2.7. But it constantly produces annoying errors on 3.6...

# -*- coding: utf-8 -*-
import urllib2
import urllib
import time
http_url = 'https://api-us.faceplusplus.com/facepp/v3/detect'
key = "please entry YOUR API_KEY"
secret = "please entry YOUR API_SECRET"
filepath = r"YOUR IMAGE PATH"
boundary = '----------%s' % hex(int(time.time() * 1000))
data = []
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_key')
data.append(key)
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_secret')
data.append(secret)
data.append('--%s' % boundary)
fr=open(filepath,'rb')
data.append('Content-Disposition: form-data; name="%s"; filename="co33.jpg"' % 'image_file')
data.append('Content-Type: %s\r\n' % 'application/octet-stream')
data.append(fr.read())
fr.close()
data.append('--%s--\r\n' % boundary)

http_body='\r\n'.join(data)
#buld http request
req=urllib2.Request(http_url)
#header
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
req.add_data(http_body)
try:
  #post data to server
  resp = urllib2.urlopen(req, timeout=5)
  #get response
  qrcont=resp.read()
  print qrcont

except urllib2.HTTPError as e:
    print e.read()

Thanks in advance for your help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dimonchik, 2019-01-28
@dimonchik2013

https://pynative.com/python-database-connection-po...

E
Egor Tyuvaev, 2017-07-17
@CulHatsker

You didn't say what kind of error you're getting, but I'm guessing it's
1) SyntaxError on print lines, because print is a function in python3. => Replace all "print ..." with "print(...)"
2) ImportError because urllib2 module is not in python3

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question