Python Requests
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
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
Example 3
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}
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
Example 5
def get_auth_token():
global token Score: 13
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
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
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
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.
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
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
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
def get_access_token(**kwargs):
""" Calls live.com authorization server with parameters passed in, deserializes the response and returns back OAuth tokens. Score: 11
r_json = json.loads(r.text)
return OAuthTokens(r_json['access_token'], int(r_json['expires_in']), r_json['refresh_token'])
Example 12
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
Example 13
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
if 'access_token' in resp:
self.token = resp['access_token']
return resp
Example 15
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
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())
if self.evaluate:
corpus, X_test, labels, y_test = train_test_split(corpus, labels, test_size=.3)
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()
Example 17
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
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
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
http://www.programcreek.com/python/example/6251/requests.post 5/14
2017-7-31 Python requests.post Examples
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
Example 21
connection.encoding = "UTF-8"
connection = json.loads(connection.text)
return connection
# ??
Example 22
Example 23
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
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
def oneTheadCatch(pOffsets):
global XSRF, HASH_ID Score: 10
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
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
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
post = requests.post
if self._session:
session = self._session()
post = session.post
self._cache()
self._callback(self._res)
Example 29
data = {
'assertion': assertion,
'audience': audience,
http://www.programcreek.com/python/example/6251/requests.post 7/14
2017-7-31 Python requests.post Examples
}
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
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
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
step = 250
for start in xrange(0, len(text_list), step):
end = start + step
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
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
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
"""
if not new_job_offers:
return
Example 36
def get_auth_token():
global token Score: 10
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
Example 38
Example 39
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
def getMe(token):
response = requests.post( Score: 10
url='https://api.telegram.org/bot' + token + "/" + method
).json()
return response;
Example 41
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
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.
Example 44
res = res.json()
self.update_cache(doc.url, 'calais', res)
return res
Example 45
return r
Example 46
Example 47
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
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
Args:
md5 - A hash.
"""
r = requests.post('http://threatbutt.io/api/md5/{0}'.format(md5))
self._output(r.text)
Example 50
def query_api(query,
api_guid, Score: 8
page=None,
endpoint="http://api.import.io/store/connector/"):
auth_credentials = read_credentials()
timeout = 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
rtext = r.text
except:
rok = False
rstatus_code = 000
rtext = "exception"
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"
Example 51
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
Example 53
"""
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
Example 55
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