0% found this document useful (0 votes)
453 views14 pages

Python requests.post Guide

The document provides examples of using the requests.post method in Python code. It lists 9 code examples extracted from open source Python projects that demonstrate different uses of requests.post, such as logging into a Google account, uploading an attachment to a note, making API requests, searching for words, creating OAuth tokens, and making calls to a ShapeShift API. Each example includes a brief description and a "Score" indicating its quality.

Uploaded by

malliwi88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
453 views14 pages

Python requests.post Guide

The document provides examples of using the requests.post method in Python code. It lists 9 code examples extracted from open source Python projects that demonstrate different uses of requests.post, such as logging into a Google account, uploading an attachment to a note, making API requests, searching for words, creating OAuth tokens, and making calls to a ShapeShift API. Each example includes a brief description and a "Score" indicating its quality.

Uploaded by

malliwi88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2017-7-31 Python requests.

post Examples

Home Top APIs Program Creek

Python [Link] Examples

The following are 55 code examples for showing how to use [Link]. They are extracted from open source Python
projects. You can click to vote up the examples you like, or click to vote down the exmaples you don't like. Your
votes will be used in our system to extract more high-quality examples.

You may also check out all available functions/classes of the module requests , or try the search function .

Example 1

From project shortimer, under directory jobs, in source file [Link].

def login(self):
form = { Score: 34
"Email": [Link],
"Passwd": [Link],
"accountType": "GOOGLE",
"source": [Link],
"service": "analytics"
}
r = [Link]("[Link] form)
[Link] = "GoogleLogin " + [Link]("(Auth=.+)$", [Link]).group(1)

Example 2

From project paperwrap-master, under directory paperwrap, in source file [Link].

def upload_attachment(self, note, path):


"""Uploads an attachment. Score: 16

:type note: dict


:type path: str
:rtype: dict
"""
[Link]('Uploading file at {} to {}'.format(path, note))
return [Link](
[Link] + API_VERSION + API_PATH['attachments'].format(
note['notebook_id'],
note['id'],
0),
files={'file': open(path, 'rb')},
headers=[Link])

Example 3

From project docli-master, under directory docli/commands, in source file base_request.py.

def do_request(self, method, url, *args, **kwargs):


Score: 14
auth_token = [Link]('token', None)
params = [Link]('params', None)
headers = [Link]('headers', None)
proxy = [Link]('proxy', None)

if not auth_token:
try:
config = [Link]()
[Link]([Link]('~/.[Link]'))
auth_token = [Link]('docli', 'auth_token') or [Link]('do_auth_token')
except:
auth_token = None

if not auth_token:
data = {'has_error':True, 'error_message':'Authentication token not provided.'}
return data

if headers:
[Link]({'Authorization': 'Bearer ' + auth_token})
else:
headers = {'Authorization': 'Bearer ' + auth_token}

if proxy:
proxy = {'http': proxy}

request_method = {'GET':[Link], 'POST': [Link], 'PUT': [Link], 'DELETE': [Link]}

request_url = self.api_url + url

req = request_method[method]

try:
res = req(request_url, headers=headers, params=params, proxies=proxy)
except ([Link], [Link]) as e:
data = {'has_error':True, 'error_message':[Link]}
return data

if res.status_code == 204:
data = {'has_error':False, 'error_message':''}
return data

try:
data = [Link]()
[Link]({'has_error':False, 'error_message':''})
except ValueError as e:
msg = "Cannot read response, %s" %([Link])
data = {'has_error':True, 'error_message':msg}

[Link] 1/14
2017-7-31 Python [Link] Examples
if not [Link]:
msg = data['message']
[Link]({'has_error':True, 'error_message':msg})

return data

Example 4

From project image_space-master, under directory imagespace/server, in source file imagebackgroundsearch_rest.py.

def _imageSearch(self, params):


return [{'id': d[0], 'score': d[1]} for d in [Link]( Score: 13
[Link]['IMAGE_SPACE_CMU_BACKGROUND_SEARCH'],
data=params['url'],
headers={
'Content-type': 'text',
'Content-length': str(len(params['url']))
},
verify=False)
.json()]

Example 5

From project networkx, under directory tools, in source file gh_api.py.

def get_auth_token():
global token Score: 13

if token is not None:


return token

import keyring
token = keyring.get_password('github', fake_username)
if token is not None:
return token

print("Please enter your github username and password. These are not "
"stored, only used to get an oAuth token. You can revoke this at "
"any time on Github.")
user = input("Username: ")
pw = [Link]("Password: ")

auth_request = {
"scopes": [
"public_repo",
"gist"
],
"note": "NetworkX tools",
"note_url": "[Link]
}
response = [Link]('[Link]
auth=(user, pw), data=[Link](auth_request))
response.raise_for_status()
token = [Link]([Link])['token']
keyring.set_password('github', fake_username, token)
return token

Example 6

From project requests, under directory , in source file test_requests.py.

def test_entry_points(self):
Score: 13
[Link]
[Link]().get
[Link]().head
[Link]
[Link]
[Link]
[Link]
[Link]

Example 7

From project hacknightbot-master, under directory , in source file [Link].

def getVerbs():
data = {'Level': 20, 'Pos': 't'} Score: 11
words = []
while len(words) < 100:
r = [Link]('{0}/RandomWordPlus'.format(url), data=data)
if [Link]('utf-8').endswith('ing'):
[Link]([Link]('utf-8'))
print('got a word: %s' % [Link])
with open('json_data/[Link]', 'w') as f:
[Link]([Link](words))

Example 8

From project configuration, under directory playbooks/util, in source file github_oauth_token.py.

def get_oauth_token(username, password, scopes, note):


""" Score: 11
Create a GitHub OAuth token with the given scopes.

[Link] 2/14
2017-7-31 Python [Link] Examples
If unsuccessful, print an error message and exit.

Returns a tuple `(token, scopes)`


"""
params = {'scopes': scopes, 'note': note}

response = response = [Link](


'[Link]
data=[Link](params),
auth=(username, password)
)

if response.status_code != 201:
print dedent("""
Could not create OAuth token.
HTTP status code: {0}
Content: {1}
""".format(response.status_code, [Link])).strip()
exit(1)

try:
token_data = [Link]()
return token_data['token'], token_data['scopes']

except TypeError:
print "Could not parse response data."
exit(1)

except KeyError:
print "Could not retrieve data from response."
exit(1)

Example 9

From project walletgenie-master, under directory core_plugins, in source file [Link].

def _call(self, httpmethod, method, *args, **kwargs):


requrl = '/{}'.format(method) Score: 11
for arg in args:
requrl += '/{}'.format(arg)
try:
if [Link]() == 'post':
postdata = [Link](kwargs)
response = [Link]('{}{}'.format([Link], requrl), headers=[Link], data=postdata)
else:
response = [Link]('{}{}'.format([Link], requrl), headers=[Link])

if int(response.status_code) != 200:
return None
output = [Link]( [Link] )
except Exception as e: # [Link]
print('\nError contacting ShapeShift servers...: {}\n'.format(e))
return None

return output

Example 10

From project SublimeBart-master, under directory lib/requests, in source file test_requests.py.

def test_entry_points(self):
Score: 11
[Link]
[Link]().get
[Link]().head
[Link]
[Link]
[Link]
[Link]
[Link]

Example 11

From project BingAds-Python-SDK-master, under directory bingads, in source file [Link].

def get_access_token(**kwargs):
""" Calls [Link] authorization server with parameters passed in, deserializes the response and returns back OAuth tokens. Score: 11

:param kwargs: OAuth parameters for authorization server call.


:return: OAuth tokens.
:rtype: OAuthTokens
"""

if 'client_secret' in kwargs and kwargs['client_secret'] is None:


del kwargs['client_secret']

r = [Link]('[Link] kwargs, verify=True)


try:
r.raise_for_status()
except Exception:
error_json = [Link]([Link])
raise OAuthTokenRequestException(error_json['error'], error_json['error_description'])

r_json = [Link]([Link])
return OAuthTokens(r_json['access_token'], int(r_json['expires_in']), r_json['refresh_token'])

Example 12

From project hepdata-master, under directory hepdata/utils, in source file [Link].

def make_robotupload_marcxml(url, marcxml, mode, **kwargs):


"""Make a robotupload request.""" Score: 11
from [Link] import make_user_agent_string
from [Link] import clean_xml

from flask import current_app


headers = {

[Link] 3/14
2017-7-31 Python [Link] Examples
"User-agent": make_user_agent_string("hepdata"),
"Content-Type": "application/marcxml+xml",
}
if url is None:
base_url = current_app.[Link]("CFG_ROBOTUPLOAD_SUBMISSION_BASEURL")
else:
base_url = url

url = [Link](base_url, "batchuploader/robotupload", mode)


return [Link](
url=url,
data=str(clean_xml(marcxml)),
headers=headers,
params=kwargs,
)

Example 13

From project haos-master, under directory haos/rally, in source file [Link].

def run_command(context, node, command, recover_command=None,


recover_timeout=0, executor="dummy", timeout=300): Score: 11
if recover_command is not None:
action = {"node": node, "command": recover_command,
"timeout": recover_timeout, "executor": executor}
context["recover_commands"].append(action)

[Link]([Link], timeout_alarm)
[Link](timeout)
if executor == "dummy":
r = [Link]("[Link]
headers={"Content-Type": "application/json"},
data=[Link]({"command": command}))
return [Link]
elif executor == "shaker":
shaker = [Link]("shaker")
if not shaker:
shaker = [Link](context["shaker_endpoint"], [],
agent_loss_timeout=600)
context["shaker"] = shaker
r = shaker.run_script(node, command)
return [Link]('stdout')

Example 14

From project python-exist-master, under directory exist, in source file [Link].

def refresh_token(self, refresh_token):


""" Score: 11
Get a new token, using the provided refresh token. Returns the new
access_token.
"""

response = [Link]('%saccess_token' % OAUTH_URL, {


'refresh_token': refresh_token,
'grant_type': 'refresh_token',
'client_id': self.client_id,
'client_secret': self.client_secret
})
resp = [Link]([Link])

if 'access_token' in resp:
[Link] = resp['access_token']

return resp

Example 15

From project bii-server-master, under directory user, in source file [Link].

def get_access_token(self, code):


payload = {'client_id': BII_GITHUB_OAUTH_CLIENT_ID, Score: 11
'client_secret': BII_GITHUB_OAUTH_CLIENT_SECRET,
'code': code}
headers = {'Accept': 'application/json'}

res = [Link]('[Link] params=payload,


headers=headers)
json = [Link]()

if "error" in json:
raise BiiException(json["error"])
if [Link]("scope", None) != [Link]:
return BiiException(json["Biicode needs your email and login"])
return json["access_token"]

Example 16

From project data-engineering-101-master, under directory , in source file [Link].

def run(self):
corpus = [] Score: 11
labels = []

vectorizer = TfidfVectorizer()

for f in [Link](): # The input() method is a wrapper around requires() that returns Target objects
with [Link]('r') as fh:
[Link]([Link]().strip())
[Link]([Link]())

corpus, X_test, labels, y_test = train_test_split(corpus, labels, test_size=.3)

if [Link]:
corpus, X_test, labels, y_test = train_test_split(corpus, labels, test_size=.3)

# output test/train splits

[Link] 4/14
2017-7-31 Python [Link] Examples
xt = [Link]()[3].open('w')
yt = [Link]()[4].open('w')

[Link](X_test, xt)
[Link](y_test, yt)
[Link]()
[Link]()

X = vectorizer.fit_transform(corpus)

fc = [Link]()[0].open('w')
fv = [Link]()[1].open('w')
fl = [Link]()[2].open('w')
[Link](X, fc)
[Link](vectorizer, fv)
[Link](','.join(labels))
[Link]()
[Link]()
[Link]()

files = {'filedata': [Link]()[1].open()}


[Link]('[Link] files=files)

Example 17

From project memegen-master, under directory memegen/routes, in source file [Link].

def track_request(title):
data = dict( Score: 10
v=1,
tid=[Link]['GOOGLE_ANALYTICS_TID'],
cid=request.remote_addr,

t='pageview',
dh='[Link]',
dp=[Link],
dt=str(title),

uip=request.remote_addr,
ua=request.user_agent.string,
dr=[Link],
)
if not [Link]['TESTING']: # pragma: no cover (manual)
[Link]("[Link] data=data)

Example 18

From project web-text-analyzer-master, under directory , in source file get_data.py.

def data_analyzer(text, source):


data = { Score: 10
'text_list': [text],
'max_keywords': 25,
'use_company_names': 1,
'expand_acronyms': 1

response = [Link](
"[Link]
data=[Link](data),
headers={'Authorization': 'Token ' + str([Link][1]),
'Content-Type': 'application/json'})

results = [Link]([Link])["result"][0]
analysis = []
for result in results:
row = {"relevance": [Link]("relevance"),
"keyword": [Link]("keyword"),
"source": source,
"datetime": [Link]("%Y-%m-%d %H:%M:%S")}
[Link](row)
return analysis

Example 19

From project login-and-pay-with-amazon-sdk-python-master, under directory pay_with_amazon, in source file payment_request.py.

def _request(self, retry_time):


[Link](retry_time) Score: 10
data = self._querystring(self._params)

r = [Link](
url=self._mws_endpoint,
data=data,
headers=self._headers,
verify=True)
self._status_code = r.status_code

if self._status_code == 200:
[Link] = True
self._should_throttle = False
[Link] = PaymentResponse([Link])
elif (self._status_code == 500 or self._status_code ==
503) and self.handle_throttle:
self._should_throttle = True
[Link] = PaymentErrorResponse(
'<error>{}</error>'.format(r.status_code))
else:
[Link] = PaymentErrorResponse([Link])

Example 20

From project karlnet, under directory consumers/sparkfun, in source file [Link].

def on_message(client, userdata, msg):


assert([Link]("/")[2] == "4369") Score: 10

[Link] 5/14
2017-7-31 Python [Link] Examples

if [Link]() - userdata.last_sent > 60:


mm = [Link]([Link]("utf-8"))
headers = {
'Content-type': 'application/x-www-form-urlencoded',
'Phant-Private-Key': userdata.private_key,
}

data = {
"temp": mm["sensors"][0]["value"],
"humidity" : mm["sensors"][1]["value"],
}
if len(mm["sensors"]) > 2:
data["channel1_temp"] = mm["sensors"][2]["value"]
else:
data["channel1_temp"] = 0

print("posting data: ", data)


resp = [Link]("[Link] % userdata.public_key, data=data, headers=headers)
resp.raise_for_status()
userdata.last_sent = [Link]()
print("got a response: ", resp)

Example 21

From project NetEaseMusic-master, under directory , in source file [Link].

def httpRequest(self, method, action, query=None, urlencoded=None, callback=None, timeout=None):


if (method == 'GET'): Score: 10
url = action if (query == None) else (action + '?' + query)
connection = [Link](url, headers=[Link], timeout=default_timeout)

elif (method == 'POST'):


connection = [Link](
action,
data=query,
headers=[Link],
timeout=default_timeout
)

[Link] = "UTF-8"
connection = [Link]([Link])
return connection

# ??

Example 22

From project pisi-farm-master, under directory client, in source file [Link].

def dosya_gonder(self, fname, r, b):


cmd = "upload" Score: 10
f = {'file': open(fname, 'rb')}
r = [Link]("%s/%s" % ([Link], cmd), files=f)
hashx = [Link]("sha1sum %s" % fname, "r").readlines()[0].split()[0].strip()
if hashx == [Link]():
return True
else:
return False

Example 23

From project Flask-GAE, under directory tests, in source file __main__.py.

def test_405_page(self):
""" Score: 10
test 405 page
"""
r = [Link]('%s/login' % [Link], allow_redirects=False)
[Link](r.status_code, 405)
soup = BeautifulSoup([Link])
[Link]([Link]('div', {'class': 'status'})[0].contents[0], '405')

Example 24

From project twitter-to-email-master, under directory , in source file [Link].

def send_digest(self):
payload = { Score: 10
'from': 'Bot <postmaster@{}>'.format([Link]['domain']),
'to': [Link],
'subject': 'Digest for {}'.format([Link]([Link]).strftime('%Y-%m-%d %H:%M')),
'html': self.html_data
}
[Link]('[Link]
.format([Link]['domain']), data=payload, auth=('api', [Link]['key']))

Example 25

From project Evi1m0-Tip-master, under directory Tip0_ZhihuFans, in source file Tip0_ZhihuSexCrawl_icon_mt.py.

def oneTheadCatch(pOffsets):
global XSRF, HASH_ID Score: 10

#print "Now Offsets:" + str(pOffsets)


_Params = [Link]({"hash_id": HASH_ID, "order_by": "created", \
"offset": pOffsets, })
_PostData = {
'method': 'next',
'params': _Params,
'_xsrf': XSRF
}

[Link] 6/14
2017-7-31 Python [Link] Examples

try_count = 0
while True:
try:
_FansCount = [Link]( \
"[Link] \
data=_PostData, cookies=COOKIES, \
timeout=15 * (try_count + 1))
try_count = 0
print "Done oneTheadCatch:" + str(pOffsets)
break
except:
print "Post Failed! Reposting...oneTheadCatch:" + str(pOffsets)
try_count += 1
[Link](3) # sleep 3 seconds to avoid network error.

return fansInfoAna(_FansCount.text)

Example 26

From project Evi1m0-Tip-master, under directory Tip0_ZhihuFans, in source file Tip0_ZhihuSexCrawl_json.py.

def oneTheadCatch(pHashID, pOffsets):


global XSRF Score: 10

#print "Now Offsets:" + str(pOffsets)


_Params = [Link]({"hash_id": pHashID, "order_by": "created", "offset": pOffsets, })
_PostData = {
'method': 'next',
'params': _Params,
'_xsrf': XSRF
}

try:
_FansCount = [Link]("[Link] data=_PostData, cookies=COOKIES,timeout=15)
except:
print "Post Failed! Reposting..."
_FansCount = [Link]("[Link] data=_PostData, cookies=COOKIES,timeout=30)

#print _FansCount.text

fansInfoAna(_FansCount.text)

Example 27

From project Evi1m0-Tip-master, under directory Tip0_ZhihuFans, in source file Tip0_ZhihuSexCrawl_icon.py.

def oneTheadCatch(pHashID, pOffsets):


global XSRF Score: 10

#print "Now Offsets:" + str(pOffsets)


_Params = [Link]({"hash_id": pHashID, "order_by": "created", "offset": pOffsets, })
_PostData = {
'method': 'next',
'params': _Params,
'_xsrf': XSRF
}

try:
_FansCount = [Link]("[Link] data=_PostData, cookies=COOKIES,timeout=15)
except:
print "Post Failed! Reposting..."
_FansCount = [Link]("[Link] data=_PostData, cookies=COOKIES,timeout=30)

#print _FansCount.text

try:
fansInfoAna(_FansCount.text)
except:
fansInfoAna(_FansCount.text)

Example 28

From project Nest_Data_Logger-master, under directory , in source file [Link].

def _login(self, headers=None):


data = {'username': [Link], 'password': [Link]} Score: 10

post = [Link]

if self._session:
session = self._session()
post = [Link]

response = post(LOGIN_URL, data=data, headers=headers)


response.raise_for_status()
self._res = [Link]()

self._cache()
self._callback(self._res)

Example 29

From project ajenti-master, under directory ajenti/plugins/main, in source file [Link].

def handle_persona_auth(self, context):


assertion = [Link]('assertion', None) Score: 10
audience = [Link]('audience', None)
if not assertion:
return [Link].respond_forbidden()

data = {
'assertion': assertion,
'audience': audience,

[Link] 7/14
2017-7-31 Python [Link] Examples
}

resp = [Link]('[Link] data=data, verify=True)

if [Link]:
verification_data = [Link]([Link])
if verification_data['status'] == 'okay':
context.respond_ok()
email = verification_data['email']
for user in [Link]():
if [Link] == email:
[Link]().login(context, [Link])
break
else:
[Link]['login-error'] = _('Email "%s" is not associated with any user') % email
return ''
[Link]['login-error'] = _('Login failed')
return context.respond_not_found()

Example 30

From project aws-saml-broker-master, under directory , in source file [Link].

def validate_user(okta_config, username, password):


r = [Link]('[Link] % okta_config['domain'], data=[Link]({ Score: 10
'username': username,
'password': password}),headers={
'Content-Type': 'application/json',
'Authorization': 'SSWS %s' % okta_config['api_token']
})
r = [Link]()

if [Link]('status') != 'SUCCESS':
raise OktaException('Login failed: %s' % [Link]('errorSummary'))

user_id = r['_embedded']['user']['id']
return r['_embedded']['user']['profile']['login'], user_id

Example 31

From project dmusic-plugin-NeteaseCloudMusic-master, under directory neteasecloudmusic, in source file netease_api.py.

def httpRequest(self, method, action, query=None, urlencoded=None, callback=None, timeout=None):


if(method == 'GET'): Score: 10
url = action if (query == None) else (action + '?' + query)
connection = [Link](url, headers=[Link],
timeout=default_timeout, cookies=[Link])

elif(method == 'POST'):
connection = [Link](
action,
data=query,
headers=[Link],
timeout=default_timeout,
cookies=[Link]
)

[Link] = "UTF-8"
connection = [Link]([Link])
return connection

# ????

Example 32

From project twitter-post-master, under directory , in source file [Link].

def classify_batch(text_list, classifier_id):


""" Score: 10
Batch classify texts
text_list -- list of texts to be classified
classifier_id -- id of the MonkeyLearn classifier to be applied to the texts
"""
results = []

step = 250
for start in xrange(0, len(text_list), step):
end = start + step

data = {'text_list': text_list[start:end]}

response = [Link](
MONKEYLEARN_CLASSIFIER_BASE_URL + classifier_id + '/classify_batch_text/',
data=[Link](data),
headers={
'Authorization': 'Token {}'.format(MONKEYLEARN_TOKEN),
'Content-Type': 'application/json'
})

try:
[Link]([Link]()['result'])
except:
print [Link]
raise

return results

Example 33

From project Reverse_HTTPS_Bot-master, under directory , in source file https_bot.py.

def send(host, content, output, proxies):


output = botID[0]+', '+content+', '+output Score: 10
if proxies is not None:
response = [Link]('[Link] data=output, verify=False, proxies=proxies, headers = headers)
return response

[Link] 8/14
2017-7-31 Python [Link] Examples
else:
response = [Link]('[Link] data=output, verify=False, headers = headers)
return response

Example 34

From project cortipy-master, under directory cortipy, in source file cortical_client.py.

def _queryAPI(self, method, resourcePath, queryParams,


postData=None, headers=None): Score: 10
url = [Link] + resourcePath
if headers is None:
headers = {}
headers['api-key'] = [Link]
response = None

if [Link] > 0:
print "\tCalling API: %s %s" % (method, url)
print "\tHeaders:\n\t%s" % [Link](headers)
print "\tQuery params:\n\t%s" % [Link](queryParams)
if method == "POST":
print "\tPost data: \n\t%s" % postData

if method == 'GET':
response = [Link](url, params=queryParams, headers=headers)
elif method == 'POST':
response = [Link](
url, params=queryParams, headers=headers, data=postData)
else:
raise RequestMethodError("Method " + method + " is not recognized.")
if response.status_code != 200:
raise UnsuccessfulEncodingError(
"Response " + str(response.status_code) + ": " + [Link])
if [Link] > 1:
print "API Response content:"
print [Link]
try:
responseObj = [Link]([Link])
except ValueError("Could not decode the query response."):
responseObj = []
return responseObj

Example 35

From project mojo-master, under directory , in source file [Link].

def send_mail(new_job_offers, api_key, api_url, send_to, send_from):


"""Send an HTML formatted email digest, listing current open job Score: 10
offers of interest.

"""
if not new_job_offers:
return

formatted_offers = ''.join([format_job_offer(offer) for offer in new_job_offers])


text = u"""
<p>Here are new job offers found on <a href="{base_url}">{base_url}</a>.</p>
{offers}""".format(base_url=BASE_URL, offers=formatted_offers)
return [Link](
api_url,
auth=("api", api_key),
data = {
"from": send_from,
"to": send_to,
"subject": "[Mojo] - %d new position%s found" % (
len(new_job_offers), 's' if len(new_job_offers) > 1 else ''),
"html": text
})

Example 36

From project Theano, under directory theano/misc, in source file gh_api.py.

def get_auth_token():
global token Score: 10

if token is not None:


return token

import keyring
token = keyring.get_password('github', fake_username)
if token is not None:
return token

print("Please enter your github username and password. These are not "
"stored, only used to get an oAuth token. You can revoke this at "
"any time on Github.")
user = input("Username: ")
pw = [Link]("Password: ")

auth_request = {
"scopes": [
"public_repo",
"gist"
],
"note": "IPython tools",
"note_url": "[Link]
}
response = [Link]('[Link]
auth=(user, pw), data=[Link](auth_request))
response.raise_for_status()
token = [Link]([Link])['token']
keyring.set_password('github', fake_username, token)
return token

[Link] 9/14
2017-7-31 Python [Link] Examples
Example 37

From project calvin-base-master, under directory calvin/utilities, in source file [Link].

def peer_setup(rt, *peers):


if not isinstance(peers[0], type("")): Score: 10
peers = peers[0]
r = [Link](
rt.control_uri + '/peer_setup', data=[Link]({'peers': peers}))
return [Link]([Link])

Example 38

From project WatchPeopleCode-master, under directory wpc, in source file email_notifications.py.

def send_message(recipient_vars, subject, text, html):


return [Link]( Score: 10
[Link]['MAILGUN_API_URL'],
auth=("api", [Link]['MAILGUN_API_KEY']),
data={"from": "WatchPeopleCode <{}>".format([Link]['NOTIFICATION_EMAIL']),
"to": recipient_vars.keys(),
"subject": subject,
"text": text,
"html": html,
"recipient-variables": ([Link](recipient_vars)),
"o:testmode": [Link]['MAILGUN_TEST_OPTION']
})

Example 39

From project eru-core-master, under directory eru/helpers, in source file [Link].

def falcon_remove_alarms(version):
for exp_id in version.falcon_expression_ids: Score: 10
try:
[Link]('%s/api/delete_expression' % FALCON_API_HOST, data={'id': exp_id})
except:
pass
del version.falcon_expression_ids

Example 40

From project scripts-master, under directory , in source file [Link].

def getMe(token):
response = [Link]( Score: 10
url='[Link] + token + "/" + method
).json()
return response;

Example 41

From project galaxy-master, under directory scripts/api, in source file upload_to_history.py.

def upload_file( base_url, api_key, history_id, filepath, **kwargs ):


full_url = base_url + '/api/tools' Score: 10

payload = {
'key' : api_key,
'tool_id' : 'upload1',
'history_id' : history_id,
}
inputs = {
'files_0|NAME' : [Link]( 'filename', [Link]( filepath ) ),
'files_0|type' : 'upload_dataset',
#TODO: the following doesn't work with [Link]
#'dbkey' : [Link]( 'dbkey', '?' ),
'dbkey' : '?',
'file_type' : [Link]( 'file_type', 'auto' ),
'ajax_upload' : u'true',
#'async_datasets': '1',
}
payload[ 'inputs' ] = [Link]( inputs )

response = None
with open( filepath, 'rb' ) as file_to_upload:
files = { 'files_0|file_data' : file_to_upload }
response = [Link]( full_url, data=payload, files=files )
return [Link]()

# -----------------------------------------------------------------------------

Example 42

From project reddit-image-download-master, under directory , in source file [Link].

def getToken(self):
client_auth = [Link](client_id, client_secret) Score: 10
post_data = {"grant_type": "password", "username": [Link], "password": [Link]}
headers = { "User-Agent": "rid/0.1 by rickstick19" }
response = [Link]("[Link] auth=client_auth, data=post_data, headers=headers)
json_dict = [Link]()
return json_dict['access_token']

Example 43

[Link] 10/14
2017-7-31 Python [Link] Examples
From project [Link], under directory libs, in source file plugin_task_bot.py.

def on_feed_download(self, feed, config):


for entry in [Link]: Score: 10
if [Link]:
[Link]("Would add %s to %s" % (entry['url'], config['host']))
continue
data = dict(
url = entry['url'],
title = entry['title'],
tags = config['tags']
)
try:
r = [Link]("[Link] data=data)
assert "task_id" in [Link]
except Exception:
[Link](entry, "Add task error")
[Link]('"%s" added to %s' % (entry['title'], config['host']))

Example 44

From project mma-dexter, under directory dexter/processing/extractors, in source file [Link].

def fetch_data(self, doc):


# First check for the (legacy) nicely formatted OpenCalais JSON. Score: 10
# We now prefer to cache the original result.
res = self.check_cache([Link], 'calais-normalised')
if not res:
# check for regular json
res = self.check_cache([Link], 'calais')
if not res:
# fetch it
# NOTE: set the ENV variable CALAIS_API_KEY before running the process
if not self.API_KEY:
raise ValueError('%s.%s.API_KEY must be defined.' % (self.__module__, self.__class__.__name__))

res = [Link]('[Link] [Link]('utf-8'),


headers={
'x-calais-licenseID': self.API_KEY,
'content-type': 'text/raw',
'accept': 'application/json',
})
if res.status_code != 200:
[Link]([Link])
res.raise_for_status()

res = [Link]()
self.update_cache([Link], 'calais', res)

# make the JSON decent and usable


res = [Link](res)

return res

Example 45

From project python-api, under directory dist/plotly-0.5.8/plotly, in source file [Link].

def signup(un, email):


''' Remote signup to [Link] and [Link] API Score: 10
Returns:
:param r with r['tmp_pw']: Temporary password to access your [Link] acount
:param r['api_key']: A key to use the API with

Full docs and examples at [Link]


:un: <string> username
:email: <string> email address
'''
payload = {'version': __version__, 'un': un, 'email': email, 'platform':'Python'}
r = [Link]('[Link] data=payload)
r.raise_for_status()
r = [Link]([Link])
if 'error' in r and r['error'] != '':
print(r['error'])
if 'warning' in r and r['warning'] != '':
[Link](r['warning'])
if 'message' in r and r['message'] != '':
print(r['message'])

return r

Example 46

From project scrypture-master, under directory scrypture, in source file scrypture_api.py.

def post(self, uri, params={}, data={}):


'''A generic method to make POST requests on the given URI.''' Score: 10
return [Link](
[Link](self.BASE_URL, uri),
params=params, data=[Link](data), verify=False,
auth=[Link], headers = {'Content-type': 'application/json', 'Accept': 'text/plain'})

Example 47

From project LiveNewsBoard-master, under directory src/lnb/feeders/jira, in source file jira_feeder.py.

def put_to_dashboard(payload):
headers = {'Content-Type': 'application/json'} Score: 10
r = [Link]('[Link]
headers=headers,
data=[Link](payload)
)
return [Link]

[Link] 11/14
2017-7-31 Python [Link] Examples

Example 48

From project unfav-master, under directory twitter, in source file [Link].

def _RequestUrl(self, url, verb, data=None):


"""Request a url. Score: 8

Args:
url:
The web location we want to retrieve.
verb:
Either POST or GET.
data:
A dict of (str, unicode) key/value pairs.

Returns:
A JSON object.
"""
if verb == 'POST':
if data.has_key('media_ids'):
url = self._BuildUrl(url, extra_params={'media_ids': data['media_ids']})
if data.has_key('media'):
try:
return [Link](
url,
files=data,
auth=self.__auth,
timeout=self._timeout
)
except [Link] as e:
raise TwitterError(str(e))
else:
try:
return [Link](
url,
data=data,
auth=self.__auth,
timeout=self._timeout
)
except [Link] as e:
raise TwitterError(str(e))
if verb == 'GET':
url = self._BuildUrl(url, extra_params=data)
try:
return [Link](
url,
auth=self.__auth,
timeout=self._timeout
)
except [Link] as e:
raise TwitterError(str(e))
return 0 # if not a POST or GET request

Example 49

From project threatbutt-master, under directory threatbutt, in source file [Link].

def bespoke_md5(self, md5):


"""Performs Bespoke MD5 lookup on an MD5. Score: 8

Args:
md5 - A hash.
"""
r = [Link]('[Link]
self._output([Link])

Example 50

From project web-text-analyzer-master, under directory , in source file importio_rsc.py.

def query_api(query,
api_guid, Score: 8
page=None,
endpoint="[Link]

auth_credentials = read_credentials()

timeout = 5

if page is not None and "webpage/url" in query["input"]:


paginated_url = paginate_url(query["input"]["webpage/url"], page)
query["input"]["webpage/url"] = paginated_url

try:
r = [Link](
endpoint + api_guid + "/_query?_user=" + auth_credentials["userGuid"] + "&_apikey=" + urllib.quote_plus(
auth_credentials["apiKey"]),
data=[Link](query), timeout=timeout)
rok = [Link]
rstatus_code = r.status_code
rtext = [Link]
except:
rok = False
rstatus_code = 000
rtext = "exception"

if rok is True and rstatus_code == 200 and "errorType" not in [Link]():


results = [Link]()
return results
else:
print "Error %s, %s on page %s , Retrying now (1)..." % (rstatus_code, rtext, query["input"]["webpage/url"])
[Link]()
[Link](2.5)

try:
r = [Link](
endpoint + api_guid + "/_query?_user=" + auth_credentials["userGuid"] + "&_apikey=" + urllib.quote_plus(
auth_credentials["apiKey"]),
data=[Link](query), timeout=timeout)
rok = [Link]
rstatus_code = r.status_code
[Link] 12/14
2017-7-31 Python [Link] Examples
rtext = [Link]

except:
rok = False
rstatus_code = 000
rtext = "exception"

if rok is True and rstatus_code == 200 and "errorType" not in [Link]():


results = [Link]()
return results
else:
print "Error %s, %s on page %s , Could not complete the query" % (rstatus_code, rtext, query["input"]["webpage/url"])
[Link]()
try:
error = [Link]([Link])["error"]
except:
try:
error = r.status_code
except:
error = "0"
return error

Example 51

From project edx-sitespeed-master, under directory , in source file [Link].

def login(email, password, base_url, auth_user=None, auth_pass=None):


""" Score: 8
Log in to the edX application via HTTP and parse sessionid from cookie.

Args:
email: Email address of edX user
password: Password for the edX user
base_url: Base url of the edX application
auth_user (Optional): Basic auth username for accessing the edX application
auth_pass (Optional): Basic auth password for accessing the edX application

Returns:
A dictionary with the data needed to create a headers file for [Link],
that will access the edX application as a logged-in user.
{
'session_key': name of the session key cookie,
'session_id': the sessionid on the edx platform
'csrf_token': the csrf token
}

Raises:
RuntimeError: If the login page is not accessible or the login fails.

"""
if (auth_user and auth_pass):
auth = (auth_user, auth_pass)
else:
auth = None

r = [Link]('{}/login'.format(base_url), auth=auth)
if r.status_code != 200:
raise RuntimeError('Failed accessing the login URL. Return code: {}'.format(r.status_code))

csrf = [Link]['csrftoken']
data = {'email': email, 'password': password}
cookies = {'csrftoken': csrf}
headers = {'referer': '{}/login'.format(base_url), 'X-CSRFToken': csrf}

r = [Link]('{}/user_api/v1/account/login_session/'.format(base_url),
data=data, cookies=cookies, headers=headers, auth=auth)

if r.status_code != 200:
raise RuntimeError('Failed logging in. Return code: {}'.format(r.status_code))
try:
session_key = 'prod-edx-sessionid'
session_id = [Link][session_key] # production
except KeyError:
session_key = 'sessionid'
session_id = [Link][session_key] # sandbox
return {'session_key' : session_key, 'session_id' : session_id, 'csrf_token' : csrf}

Example 52

From project python-for-hackers-master, under directory codes, in source file [Link].

def cracker(tn, q):


while not exit_flag: Score: 7
queue_lock.acquire()
if not work_queue.empty():
u, p = [Link]()
data = {'username': u, 'password': p}
response = [Link]("[Link] data)
if "denied" not in [Link]()['msg']:
[Link]((u, p, tn))
queue_lock.release()
else:
queue_lock.release()

Example 53

From project circonus-master, under directory circonus, in source file [Link].

def create(self, resource_type, data):


"""Create the resource type with ``data`` via :func:`[Link]`. Score: 7

:param str resource_type: The resource type to create.


:param dict data: The data used to create the resource.
:rtype: :class:`[Link]`

"""
return [Link](get_api_url(resource_type), data=[Link](data), headers=self.api_headers)

[Link] 13/14
2017-7-31 Python [Link] Examples
Example 54

From project SDP-group-2-master, under directory planning, in source file [Link].

def send_async_heartbeat(self, payload_json):


r = [Link]('[Link] data=dict(payload=payload_json)) Score: 6
print r

Example 55

From project question-master, under directory , in source file [Link].

def airgram_check(email, id, msg="Hi! You've been added to Question. Swipe here to verify"):
Score:verify
resp = [Link]("[Link] data={'email': email, 'msg': msg, "url": URL + "/verify/" + id}, 5
return resp["status"] != "error", resp["error_msg"] if "error_msg" in resp else None

[Link] 14/14

You might also like