Python requests.post Guide
Python requests.post Guide
post 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
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
Example 3
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}
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
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 = [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
def test_entry_points(self):
Score: 13
[Link]
[Link]().get
[Link]().head
[Link]
[Link]
[Link]
[Link]
[Link]
Example 7
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
[Link] 2/14
2017-7-31 Python [Link] 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, [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
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
def test_entry_points(self):
Score: 11
[Link]
[Link]().get
[Link]().head
[Link]
[Link]
[Link]
[Link]
[Link]
Example 11
def get_access_token(**kwargs):
""" Calls [Link] authorization server with parameters passed in, deserializes the response and returns back OAuth tokens. Score: 11
r_json = [Link]([Link])
return OAuthTokens(r_json['access_token'], int(r_json['expires_in']), r_json['refresh_token'])
Example 12
[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
Example 13
[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
if 'access_token' in resp:
[Link] = resp['access_token']
return resp
Example 15
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
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]())
if [Link]:
corpus, X_test, labels, y_test = train_test_split(corpus, labels, test_size=.3)
[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]()
Example 17
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
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
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
[Link] 5/14
2017-7-31 Python [Link] 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
[Link] = "UTF-8"
connection = [Link]([Link])
return connection
# ??
Example 22
Example 23
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
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
def oneTheadCatch(pOffsets):
global XSRF, HASH_ID Score: 10
[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
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
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
post = [Link]
if self._session:
session = self._session()
post = [Link]
self._cache()
self._callback(self._res)
Example 29
data = {
'assertion': assertion,
'audience': audience,
[Link] 7/14
2017-7-31 Python [Link] Examples
}
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
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
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
step = 250
for start in xrange(0, len(text_list), step):
end = start + step
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
[Link] 8/14
2017-7-31 Python [Link] Examples
else:
response = [Link]('[Link] data=output, verify=False, headers = headers)
return response
Example 34
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
"""
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 = [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
Example 38
Example 39
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
def getMe(token):
response = [Link]( Score: 10
url='[Link] + token + "/" + method
).json()
return response;
Example 41
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
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.
Example 44
res = [Link]()
self.update_cache([Link], '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 = [Link]('[Link]
headers=headers,
data=[Link](payload)
)
return [Link]
[Link] 11/14
2017-7-31 Python [Link] 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 [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
Args:
md5 - A hash.
"""
r = [Link]('[Link]
self._output([Link])
Example 50
def query_api(query,
api_guid, Score: 8
page=None,
endpoint="[Link]
auth_credentials = read_credentials()
timeout = 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
rtext = [Link]
except:
rok = False
rstatus_code = 000
rtext = "exception"
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"
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 [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
Example 53
"""
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
Example 55
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