You are on page 1of 14

2017-7-31 Python requests.

post Examples

Home Top APIs Program Creek

Python requests.post Examples

The following are 55 code examples for showing how to use requests.post. 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 analytics.py.

def login(self):
form = { Score: 34
"Email": self.username,
"Passwd": self.password,
"accountType": "GOOGLE",
"source": self.source,
"service": "analytics"
}
r = requests.post("https://www.google.com/accounts/ClientLogin", form)
self.auth = "GoogleLogin " + re.search("(Auth=.+)$", r.content).group(1)

Example 2

From project paperwrap-master, under directory paperwrap, in source file wrapper.py.

def upload_attachment(self, note, path):


"""Uploads an attachment. Score: 16

:type note: dict


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

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 = kwargs.get('token', None)
params = kwargs.get('params', None)
headers = kwargs.get('headers', None)
proxy = kwargs.get('proxy', None)

if not auth_token:
try:
config = ConfigParser.ConfigParser()
config.read(os.path.expanduser('~/.do.cfg'))
auth_token = config.get('docli', 'auth_token') or os.getenv('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:
headers.update({'Authorization': 'Bearer ' + auth_token})
else:
headers = {'Authorization': 'Bearer ' + auth_token}

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

request_method = {'GET':requests.get, 'POST': requests.post, 'PUT': requests.put, 'DELETE': requests.delete}

request_url = self.api_url + url

req = request_method[method]

try:
res = req(request_url, headers=headers, params=params, proxies=proxy)
except (requests.exceptions.ConnectionError, requests.exceptions.RequestException) as e:
data = {'has_error':True, 'error_message':e.message}
return data

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

try:
data = res.json()
data.update({'has_error':False, 'error_message':''})
except ValueError as e:
msg = "Cannot read response, %s" %(e.message)
data = {'has_error':True, 'error_message':msg}

http://www.programcreek.com/python/example/6251/requests.post 1/14
2017-7-31 Python requests.post Examples
if not res.ok:
msg = data['message']
data.update({'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 requests.post( Score: 13
os.environ['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 = getpass.getpass("Password: ")

auth_request = {
"scopes": [
"public_repo",
"gist"
],
"note": "NetworkX tools",
"note_url": "https://github.com/networkx/networkx/tree/master/tools",
}
response = requests.post('https://api.github.com/authorizations',
auth=(user, pw), data=json.dumps(auth_request))
response.raise_for_status()
token = json.loads(response.text)['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
requests.session
requests.session().get
requests.session().head
requests.get
requests.head
requests.put
requests.patch
requests.post

Example 7

From project hacknightbot-master, under directory , in source file getMaterials.py.

def getVerbs():
data = {'Level': 20, 'Pos': 't'} Score: 11
words = []
while len(words) < 100:
r = requests.post('{0}/RandomWordPlus'.format(url), data=data)
if r.content.decode('utf-8').endswith('ing'):
words.append(r.content.decode('utf-8'))
print('got a word: %s' % r.content)
with open('json_data/verbs.json', 'w') as f:
f.write(json.dumps(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.

http://www.programcreek.com/python/example/6251/requests.post 2/14
2017-7-31 Python requests.post Examples
If unsuccessful, print an error message and exit.

Returns a tuple `(token, scopes)`


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

response = response = requests.post(


'https://api.github.com/authorizations',
data=json.dumps(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, response.text)).strip()
exit(1)

try:
token_data = response.json()
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 shapeshift.py.

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


requrl = '/{}'.format(method) Score: 11
for arg in args:
requrl += '/{}'.format(arg)
try:
if httpmethod.lower() == 'post':
postdata = json.dumps(kwargs)
response = requests.post('{}{}'.format(self.baseurl, requrl), headers=self.headers, data=postdata)
else:
response = requests.get('{}{}'.format(self.baseurl, requrl), headers=self.headers)

if int(response.status_code) != 200:
return None
output = json.loads( response.text )
except Exception as e: # requests.exceptions.ConnectionError
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
requests.session
requests.session().get
requests.session().head
requests.get
requests.head
requests.put
requests.patch
requests.post

Example 11

From project BingAds-Python-SDK-master, under directory bingads, in source file authorization.py.

def get_access_token(**kwargs):
""" Calls live.com 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 = requests.post('https://login.live.com/oauth20_token.srf', kwargs, verify=True)


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

r_json = json.loads(r.text)
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 robotupload.py.

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


"""Make a robotupload request.""" Score: 11
from invenio.utils.url import make_user_agent_string
from hepdata.utils.text import clean_xml

from flask import current_app


headers = {

http://www.programcreek.com/python/example/6251/requests.post 3/14
2017-7-31 Python requests.post Examples
"User-agent": make_user_agent_string("hepdata"),
"Content-Type": "application/marcxml+xml",
}
if url is None:
base_url = current_app.config.get("CFG_ROBOTUPLOAD_SUBMISSION_BASEURL")
else:
base_url = url

url = os.path.join(base_url, "batchuploader/robotupload", mode)


return requests.post(
url=url,
data=str(clean_xml(marcxml)),
headers=headers,
params=kwargs,
)

Example 13

From project haos-master, under directory haos/rally, in source file utils.py.

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)

signal.signal(signal.SIGALRM, timeout_alarm)
signal.alarm(timeout)
if executor == "dummy":
r = requests.post("http://{0}/run_command".format(node),
headers={"Content-Type": "application/json"},
data=json.dumps({"command": command}))
return r.text
elif executor == "shaker":
shaker = context.get("shaker")
if not shaker:
shaker = lib.Shaker(context["shaker_endpoint"], [],
agent_loss_timeout=600)
context["shaker"] = shaker
r = shaker.run_script(node, command)
return r.get('stdout')

Example 14

From project python-exist-master, under directory exist, in source file auth.py.

def refresh_token(self, refresh_token):


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

response = requests.post('%saccess_token' % OAUTH_URL, {


'refresh_token': refresh_token,
'grant_type': 'refresh_token',
'client_id': self.client_id,
'client_secret': self.client_secret
})
resp = json.loads(response.content)

if 'access_token' in resp:
self.token = resp['access_token']

return resp

Example 15

From project bii-server-master, under directory user, in source file oauth.py.

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 = requests.post('https://github.com/login/oauth/access_token', params=payload,


headers=headers)
json = res.json()

if "error" in json:
raise BiiException(json["error"])
if json.get("scope", None) != self.scope:
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 ml-pipeline.py.

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

vectorizer = TfidfVectorizer()

for f in self.input(): # The input() method is a wrapper around requires() that returns Target objects
with f.open('r') as fh:
labels.append(fh.readline().strip())
corpus.append(fh.read())

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

if self.evaluate:
corpus, X_test, labels, y_test = train_test_split(corpus, labels, test_size=.3)

# output test/train splits

http://www.programcreek.com/python/example/6251/requests.post 4/14
2017-7-31 Python requests.post Examples
xt = self.output()[3].open('w')
yt = self.output()[4].open('w')

pickle.dump(X_test, xt)
pickle.dump(y_test, yt)
xt.close()
yt.close()

X = vectorizer.fit_transform(corpus)

fc = self.output()[0].open('w')
fv = self.output()[1].open('w')
fl = self.output()[2].open('w')
pickle.dump(X, fc)
pickle.dump(vectorizer, fv)
fl.write(','.join(labels))
fc.close()
fv.close()
fl.close()

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


requests.post('http://0.0.0.0:8081/vectorizer', files=files)

Example 17

From project memegen-master, under directory memegen/routes, in source file image.py.

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

t='pageview',
dh='memegen.link',
dp=request.path,
dt=str(title),

uip=request.remote_addr,
ua=request.user_agent.string,
dr=request.referrer,
)
if not app.config['TESTING']: # pragma: no cover (manual)
requests.post("http://www.google-analytics.com/collect", 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 = requests.post(
"https://api.monkeylearn.com/v2/extractors/ex_eV2dppYE/extract/",
data=json.dumps(data),
headers={'Authorization': 'Token ' + str(sys.argv[1]),
'Content-Type': 'application/json'})

results = json.loads(response.text)["result"][0]
analysis = []
for result in results:
row = {"relevance": result.get("relevance"),
"keyword": result.get("keyword"),
"source": source,
"datetime": time.strftime("%Y-%m-%d %H:%M:%S")}
analysis.append(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):


time.sleep(retry_time) Score: 10
data = self._querystring(self._params)

r = requests.post(
url=self._mws_endpoint,
data=data,
headers=self._headers,
verify=True)
self._status_code = r.status_code

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

Example 20

From project karlnet, under directory consumers/sparkfun, in source file output-sparkfun.py.

def on_message(client, userdata, msg):


assert(msg.topic.split("/")[2] == "4369") Score: 10

http://www.programcreek.com/python/example/6251/requests.post 5/14
2017-7-31 Python requests.post Examples

if time.time() - userdata.last_sent > 60:


mm = json.loads(msg.payload.decode("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 = requests.post("http://data.sparkfun.com/input/%s" % userdata.public_key, data=data, headers=headers)
resp.raise_for_status()
userdata.last_sent = time.time()
print("got a response: ", resp)

Example 21

From project NetEaseMusic-master, under directory , in source file 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 = requests.get(url, headers=self.header, timeout=default_timeout)

elif (method == 'POST'):


connection = requests.post(
action,
data=query,
headers=self.header,
timeout=default_timeout
)

connection.encoding = "UTF-8"
connection = json.loads(connection.text)
return connection

# ??

Example 22

From project pisi-farm-master, under directory client, in source file gonullu.py.

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


cmd = "upload" Score: 10
f = {'file': open(fname, 'rb')}
r = requests.post("%s/%s" % (self.url, cmd), files=f)
hashx = os.popen("sha1sum %s" % fname, "r").readlines()[0].split()[0].strip()
if hashx == r.text.strip():
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 = requests.post('%s/login' % self.url, allow_redirects=False)
self.assertEqual(r.status_code, 405)
soup = BeautifulSoup(r.content)
self.assertEqual(soup.findAll('div', {'class': 'status'})[0].contents[0], '405')

Example 24

From project twitter-to-email-master, under directory , in source file aggregator.py.

def send_digest(self):
payload = { Score: 10
'from': 'Bot <postmaster@{}>'.format(self.mailgun['domain']),
'to': self.email,
'subject': 'Digest for {}'.format(date.fromtimestamp(self.now).strftime('%Y-%m-%d %H:%M')),
'html': self.html_data
}
requests.post('https://api.mailgun.net/v2/{}/messages'
.format(self.mailgun['domain']), data=payload, auth=('api', self.mailgun['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 = json.dumps({"hash_id": HASH_ID, "order_by": "created", \
"offset": pOffsets, })
_PostData = {
'method': 'next',
'params': _Params,
'_xsrf': XSRF
}

http://www.programcreek.com/python/example/6251/requests.post 6/14
2017-7-31 Python requests.post Examples

try_count = 0
while True:
try:
_FansCount = requests.post( \
"http://www.zhihu.com/node/ProfileFollowersListV2", \
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
time.sleep(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 = json.dumps({"hash_id": pHashID, "order_by": "created", "offset": pOffsets, })
_PostData = {
'method': 'next',
'params': _Params,
'_xsrf': XSRF
}

try:
_FansCount = requests.post("http://www.zhihu.com/node/ProfileFollowersListV2", data=_PostData, cookies=COOKIES,timeout=15)
except:
print "Post Failed! Reposting..."
_FansCount = requests.post("http://www.zhihu.com/node/ProfileFollowersListV2", 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 = json.dumps({"hash_id": pHashID, "order_by": "created", "offset": pOffsets, })
_PostData = {
'method': 'next',
'params': _Params,
'_xsrf': XSRF
}

try:
_FansCount = requests.post("http://www.zhihu.com/node/ProfileFollowersListV2", data=_PostData, cookies=COOKIES,timeout=15)
except:
print "Post Failed! Reposting..."
_FansCount = requests.post("http://www.zhihu.com/node/ProfileFollowersListV2", 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 nest.py.

def _login(self, headers=None):


data = {'username': self.username, 'password': self.password} Score: 10

post = requests.post

if self._session:
session = self._session()
post = session.post

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


response.raise_for_status()
self._res = response.json()

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

Example 29

From project ajenti-master, under directory ajenti/plugins/main, in source file main.py.

def handle_persona_auth(self, context):


assertion = context.query.getvalue('assertion', None) Score: 10
audience = context.query.getvalue('audience', None)
if not assertion:
return self.context.respond_forbidden()

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

http://www.programcreek.com/python/example/6251/requests.post 7/14
2017-7-31 Python requests.post Examples
}

resp = requests.post('https://verifier.login.persona.org/verify', data=data, verify=True)

if resp.ok:
verification_data = json.loads(resp.content)
if verification_data['status'] == 'okay':
context.respond_ok()
email = verification_data['email']
for user in ajenti.config.tree.users.values():
if user.email == email:
AuthenticationMiddleware.get().login(context, user.name)
break
else:
context.session.data['login-error'] = _('Email "%s" is not associated with any user') % email
return ''
context.session.data['login-error'] = _('Login failed')
return context.respond_not_found()

Example 30

From project aws-saml-broker-master, under directory , in source file okta.py.

def validate_user(okta_config, username, password):


r = requests.post('https://%s/api/v1/authn' % okta_config['domain'], data=json.dumps({ Score: 10
'username': username,
'password': password}),headers={
'Content-Type': 'application/json',
'Authorization': 'SSWS %s' % okta_config['api_token']
})
r = r.json()

if r.get('status') != 'SUCCESS':
raise OktaException('Login failed: %s' % r.get('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 = requests.get(url, headers=self.header,
timeout=default_timeout, cookies=self.cookies)

elif(method == 'POST'):
connection = requests.post(
action,
data=query,
headers=self.header,
timeout=default_timeout,
cookies=self.cookies
)

connection.encoding = "UTF-8"
connection = json.loads(connection.text)
return connection

# ????

Example 32

From project twitter-post-master, under directory , in source file Twitter-v3.py.

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 = requests.post(
MONKEYLEARN_CLASSIFIER_BASE_URL + classifier_id + '/classify_batch_text/',
data=json.dumps(data),
headers={
'Authorization': 'Token {}'.format(MONKEYLEARN_TOKEN),
'Content-Type': 'application/json'
})

try:
results.extend(response.json()['result'])
except:
print response.text
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 = requests.post('https://'+host+'/out', data=output, verify=False, proxies=proxies, headers = headers)
return response

http://www.programcreek.com/python/example/6251/requests.post 8/14
2017-7-31 Python requests.post Examples
else:
response = requests.post('https://'+host+'/out', 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 = self.apiUrl + resourcePath
if headers is None:
headers = {}
headers['api-key'] = self.apiKey
response = None

if self.verbosity > 0:
print "\tCalling API: %s %s" % (method, url)
print "\tHeaders:\n\t%s" % json.dumps(headers)
print "\tQuery params:\n\t%s" % json.dumps(queryParams)
if method == "POST":
print "\tPost data: \n\t%s" % postData

if method == 'GET':
response = requests.get(url, params=queryParams, headers=headers)
elif method == 'POST':
response = requests.post(
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) + ": " + response.content)
if self.verbosity > 1:
print "API Response content:"
print response.content
try:
responseObj = json.loads(response.content)
except ValueError("Could not decode the query response."):
responseObj = []
return responseObj

Example 35

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

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 requests.post(
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 = getpass.getpass("Password: ")

auth_request = {
"scopes": [
"public_repo",
"gist"
],
"note": "IPython tools",
"note_url": "https://github.com/ipython/ipython/tree/master/tools",
}
response = requests.post('https://api.github.com/authorizations',
auth=(user, pw), data=json.dumps(auth_request))
response.raise_for_status()
token = json.loads(response.text)['token']
keyring.set_password('github', fake_username, token)
return token

http://www.programcreek.com/python/example/6251/requests.post 9/14
2017-7-31 Python requests.post Examples
Example 37

From project calvin-base-master, under directory calvin/utilities, in source file utils.py.

def peer_setup(rt, *peers):


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

Example 38

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

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


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

Example 39

From project eru-core-master, under directory eru/helpers, in source file falcon.py.

def falcon_remove_alarms(version):
for exp_id in version.falcon_expression_ids: Score: 10
try:
requests.post('%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 taiyiBatteryBot.py.

def getMe(token):
response = requests.post( Score: 10
url='https://api.telegram.org/bot' + 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' : kwargs.get( 'filename', os.path.basename( filepath ) ),
'files_0|type' : 'upload_dataset',
#TODO: the following doesn't work with tools.py
#'dbkey' : kwargs.get( 'dbkey', '?' ),
'dbkey' : '?',
'file_type' : kwargs.get( 'file_type', 'auto' ),
'ajax_upload' : u'true',
#'async_datasets': '1',
}
payload[ 'inputs' ] = json.dumps( inputs )

response = None
with open( filepath, 'rb' ) as file_to_upload:
files = { 'files_0|file_data' : file_to_upload }
response = requests.post( full_url, data=payload, files=files )
return response.json()

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

Example 42

From project reddit-image-download-master, under directory , in source file rid.py.

def getToken(self):
client_auth = requests.auth.HTTPBasicAuth(client_id, client_secret) Score: 10
post_data = {"grant_type": "password", "username": self.username, "password": self.password}
headers = { "User-Agent": "rid/0.1 by rickstick19" }
response = requests.post("https://www.reddit.com/api/v1/access_token", auth=client_auth, data=post_data, headers=headers)
json_dict = response.json()
return json_dict['access_token']

Example 43

http://www.programcreek.com/python/example/6251/requests.post 10/14
2017-7-31 Python requests.post Examples
From project lixian.xunlei, under directory libs, in source file plugin_task_bot.py.

def on_feed_download(self, feed, config):


for entry in feed.accepted: Score: 10
if feed.manager.options.test:
log.info("Would add %s to %s" % (entry['url'], config['host']))
continue
data = dict(
url = entry['url'],
title = entry['title'],
tags = config['tags']
)
try:
r = requests.post("http://"+config['host']+"/add_task", data=data)
assert "task_id" in r.content
except Exception:
feed.fail(entry, "Add task error")
log.info('"%s" added to %s' % (entry['title'], config['host']))

Example 44

From project mma-dexter, under directory dexter/processing/extractors, in source file calais.py.

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(doc.url, 'calais-normalised')
if not res:
# check for regular json
res = self.check_cache(doc.url, '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 = requests.post('http://api.opencalais.com/tag/rs/enrich', doc.text.encode('utf-8'),


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

res = res.json()
self.update_cache(doc.url, 'calais', res)

# make the JSON decent and usable


res = self.normalise(res)

return res

Example 45

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

def signup(un, email):


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

Full docs and examples at https://plot.ly/API


:un: <string> username
:email: <string> email address
'''
payload = {'version': __version__, 'un': un, 'email': email, 'platform':'Python'}
r = requests.post('https://plot.ly/apimkacct', data=payload)
r.raise_for_status()
r = json.loads(r.text)
if 'error' in r and r['error'] != '':
print(r['error'])
if 'warning' in r and r['warning'] != '':
warnings.warn(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 requests.post(
urlparse.urljoin(self.BASE_URL, uri),
params=params, data=json.dumps(data), verify=False,
auth=self.auth, 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 = requests.post('http://localhost:5000/lwb/api/v1.0/posts',
headers=headers,
data=json.dumps(payload)
)
return r.content

http://www.programcreek.com/python/example/6251/requests.post 11/14
2017-7-31 Python requests.post Examples

Example 48

From project unfav-master, under directory twitter, in source file api.py.

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 requests.post(
url,
files=data,
auth=self.__auth,
timeout=self._timeout
)
except requests.RequestException as e:
raise TwitterError(str(e))
else:
try:
return requests.post(
url,
data=data,
auth=self.__auth,
timeout=self._timeout
)
except requests.RequestException as e:
raise TwitterError(str(e))
if verb == 'GET':
url = self._BuildUrl(url, extra_params=data)
try:
return requests.get(
url,
auth=self.__auth,
timeout=self._timeout
)
except requests.RequestException 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 threatbutt.py.

def bespoke_md5(self, md5):


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

Args:
md5 - A hash.
"""
r = requests.post('http://threatbutt.io/api/md5/{0}'.format(md5))
self._output(r.text)

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="http://api.import.io/store/connector/"):

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 = requests.post(
endpoint + api_guid + "/_query?_user=" + auth_credentials["userGuid"] + "&_apikey=" + urllib.quote_plus(
auth_credentials["apiKey"]),
data=json.dumps(query), timeout=timeout)
rok = r.ok
rstatus_code = r.status_code
rtext = r.text
except:
rok = False
rstatus_code = 000
rtext = "exception"

if rok is True and rstatus_code == 200 and "errorType" not in r.json():


results = r.json()
return results
else:
print "Error %s, %s on page %s , Retrying now (1)..." % (rstatus_code, rtext, query["input"]["webpage/url"])
sys.stdout.flush()
time.sleep(2.5)

try:
r = requests.post(
endpoint + api_guid + "/_query?_user=" + auth_credentials["userGuid"] + "&_apikey=" + urllib.quote_plus(
auth_credentials["apiKey"]),
data=json.dumps(query), timeout=timeout)
rok = r.ok
rstatus_code = r.status_code
http://www.programcreek.com/python/example/6251/requests.post 12/14
2017-7-31 Python requests.post Examples
rtext = r.text

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

if rok is True and rstatus_code == 200 and "errorType" not in r.json():


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

Example 51

From project edx-sitespeed-master, under directory , in source file edx-sitespeed.py.

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 sitespeed.io,
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 = requests.get('{}/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 = r.cookies['csrftoken']
data = {'email': email, 'password': password}
cookies = {'csrftoken': csrf}
headers = {'referer': '{}/login'.format(base_url), 'X-CSRFToken': csrf}

r = requests.post('{}/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 = r.cookies[session_key] # production
except KeyError:
session_key = 'sessionid'
session_id = r.cookies[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 ex7.py.

def cracker(tn, q):


while not exit_flag: Score: 7
queue_lock.acquire()
if not work_queue.empty():
u, p = q.get()
data = {'username': u, 'password': p}
response = requests.post("http://localhost:8000", data)
if "denied" not in response.json()['msg']:
cracked.append((u, p, tn))
queue_lock.release()
else:
queue_lock.release()

Example 53

From project circonus-master, under directory circonus, in source file client.py.

def create(self, resource_type, data):


"""Create the resource type with ``data`` via :func:`requests.post`. Score: 7

:param str resource_type: The resource type to create.


:param dict data: The data used to create the resource.
:rtype: :class:`requests.Response`

"""
return requests.post(get_api_url(resource_type), data=json.dumps(data), headers=self.api_headers)

http://www.programcreek.com/python/example/6251/requests.post 13/14
2017-7-31 Python requests.post Examples
Example 54

From project SDP-group-2-master, under directory planning, in source file debugger.py.

def send_async_heartbeat(self, payload_json):


r = requests.post('https://robot-heartbeat.herokuapp.com/set/', data=dict(payload=payload_json)) Score: 6
print r

Example 55

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

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

http://www.programcreek.com/python/example/6251/requests.post 14/14

You might also like