I am using requests 2.12.1 library in Python 2.7 and Django 1.10 for consume web services. When I use a session for save cookies and use persistence, and pass 10 seconds ~ without use any web service, my view regenerates the object requests.Session()...
This makes web service doesn't serve me, because my view has changed the cookies.
This is my Views.py:
client_session = requests.Session()
#watch_login
def loginUI(request):
response = client_session.post(URL_API+'login/', data={'username': username, 'password': password,})
json_login = response.json()
#login_required(login_url="/login/")
def home(request):
response_statistics = client_session.get(URL_API+'statistics/')
log('ClientSession: '+str(client_session))
try:
json_statistics = response_statistics.json()
except ValueError:
log('ExcepcionClientSession: '+str(client_session))
return logoutUI(request)
return render(request, "UI/home.html", {
'phone_calls' : json_statistics['phone_calls'],
'mobile_calls' : json_statistics['mobile_calls'],
'other_calls' : json_statistics['other_calls'],
'top_called_phones' : json_statistics['top_called_phones'],
'call_ranges_week' : json_statistics['call_ranges_week'],
'call_ranges_weekend' : json_statistics['call_ranges_weekend'],
'access_data' : accessData(request.user.username),
})
def userFeaturesFormInit(clientRequest):
log('FeaturesClientSession: '+str(client_session))
response = client_session.get(URL_API+'features/')
try:
json_features = response.json()
except ValueError as e:
log('ExcepcionFeaturesClientSession: '+str(client_session))
raise e
Thank you.
I fixed it specifying cookies manually, and saving it in the request.
client_session = requests.Session()
response = client_session.post(URL_API+'login/', {'username': username, 'password': password,})
request.session['cookiecsrf'] = client_session.cookies['csrftoken']
request.session['cookiesession'] = client_session.cookies['sessionid']
And sending it in the gets/posts:
cookies = {'csrftoken' : request.session['cookiecsrf'], 'sessionid': request.session['cookiesession']}
response = requests.get(URL, cookies=cookies)
Related
I have been attempting to solve this far too longer than id like to admit, I think the problem is how the data is being parsed with json and being interoperated via the API, as I do not have the same issue with the first function, but run into it with the second. Any help will be great.
import urllib, requests, json
def generateUserKey(username, password):
global devKey
return urllib.request.urlopen("https://pastebin.com/api/api_login.php",
urllib.parse.urlencode({"api_dev_key": devKey, "api_user_name": username, "api_user_password": password}).encode()).read()
def paste(userKey, text):
global devKey
datA = json.dumps({"api_dev_key": devKey, "api_paste_code": text, "api_user_key": userKey, "api_paste_name": "lol", "api_paste_format": "none", "api_paste_private": int(1), "api_paste_expire_date": "10M" })
resp = requests.post(url="https://pastebin.com/api/api_post.php", json=datA, data=datA)
print(resp.text)
key = generateUserKey(devKey, userName, passWord)
print(key)
paste(key, testString)
when ran I generate the following:
c0ce26a1c46d5fff3a254e519003ebb0
Bad API request, invalid api_dev_key
None
the dev key isnt invalid as its being used in the previous function to login and obtain a session key, so this is where I am stuck. Any help?
this could help:
import requests # see https://2.python-requests.org/en/master/
import json
def generateUserKey(data):
login = requests.post("https://pastebin.com/api/api_login.php", data=data)
print("Login status: ", login.status_code if login.status_code != 200 else "OK/200")
print("User token: ", login.text)
return login.text
def paste(data):
r = requests.post("https://pastebin.com/api/api_post.php", data)
print("Paste send: ", r.status_code if r.status_code != 200 else "OK/200")
print("Paste URL: ", r.text)
key = 'your key'
text = "hi"
t_title = "title of paste"
login_data = {
'api_dev_key': key,
'api_user_name': 'username',
'api_user_password': 'password'
}
data = {
'api_option': 'paste',
'api_dev_key': key,
'api_paste_code': text,
'api_paste_name': t_title,
'api_user_key': None,
# 'api_paste_expire_date': 'see_https://pastebin.com/api', # optional
# 'api_paste_private': 1, # 0 = public, 1 = unlisted, 2 = private
'api_user_key': generateUserKey(login_data)
# see_https://pastebin.com/api fro all the other arguments you can add
}
# if your data is already in json format, you can use json.dumps(data)
# data = json.dumps(data) # and now its a dict, and it can be feed to the requests.post
paste(data)
if you have any questions don't hesitate to ask
I'm brand new to python and api as well.
I'm trying to use a endpoint we have at work.
We have an API we are using a lot, we also have an UI. But using the UI we can only extract 10.000 records at the time.
There is no limit on the api.
I have found a small piece of code - but i need to add a nextpagetoken.
My code looks like this:
login_url = 'https://api.ubsend.io/v1/auth/login'
username = 'xxxxx'
password = 'xxxxx'
omitClaims = "true"
session = requests.Session()
session.headers['Accept'] = "application/json; charset=UTF-8"
response = session.post(
login_url,
json={'username': username, 'password': password},
headers={'VERSION': '3'},
)
response.raise_for_status()
response_data = response.json()
print(response_data)
This gives me the AccessToken.
Then I call:
getevents = 'https://api.ubsend.io/v1/reporting/shipments?'
data ={'client_id': 13490, 'created_after': '2020-05-01T00:00', 'created_before': '2021-05-02T00:00'} req.prepare_url(getevents, data)
events = requests.get(req.url, headers={'Authorization' : 'Bearer ' + response_data['accessToken'], Content-Type': 'application/json'})
events.json()
Which returns:
'nextPageToken': 'NjA4ZDc3YzNkMjBjODgyYjBhMWVkMTVkLDE2MTk4ODM5NzA3MDE='}
So I want to loop my script - until nextPageToken is blank ....
Any thoughts?
Edit thanks for the update. I think this might be the solution we're looking for. You might have to do some poking around to figure out exactly what the name of the page_token URL parameter should be.
has_next = True
getevents = 'https://api.ubsend.io/v1/reporting/shipments?'
token = None
while has_next:
data ={'client_id': 13490, 'created_after': '2020-05-01T00:00', 'created_before': '2021-05-02T00:00'}
if token:
# I don't know the proper name for this URL parameter.
data['page_token'] = token
req.prepare_url(getevents, data)
events = requests.get(req.url, headers={'Authorization' : 'Bearer ' + response_data['accessToken'], Content-Type: 'application/json'})
token = events.json().get('nextPageToken')
if not token:
has_next = False
I made a slight typo. It should be events.json().get('nextPageToken') I believe.
Let me know if this works.
I use pytest-django to do unit test on my django project. The view is
def news(request):
"""
Interface for newslist
"""
page = 1
if request.method == 'POST':
content = request.body
try:
content = json.loads(content)
except ValueError as error:
return err_response("Value Error of post: {}".format(error))
if 'page' in content:
page = content['page']
articlelist = Article.objects.all().order_by('-time')
paginator = Paginator(articlelist, 10)
try:
current_list = paginator.page(page)
except InvalidPage as error:
return err_response(error)
# coping with the paginator
...
newsnum = len(Article.objects.all())
return JsonResponse({
'newsnum': newsnum,
'pagelist': list(pagelist),
'data': [{
'title': newsitem.title,
'source': newsitem.source,
'time': newsitem.time.strftime("%Y-%m-%d %H:%M:%S"),
'content': newsitem.content,
'href': newsitem.href,
'image': newsitem.image,
} for newsitem in current_list]
}, status=200)
When I use pytest-django to test it
#pytest.mark.django_db
def test_view_news(client):
"""
Test view news
"""
url = reverse("news")
data = {
'page': 1
}
response = client.post(url, data=data)
assert response.status_code == 200
It gives Bad Request and code 400. But when I use client.get(), the response is normal (code 200).In the settings, I already set
DEBUG = True
ALLOWED_HOSTS = ['*']
Can anyone tells me what happened?
Override the default server_name used by client
Just override the default server name used by client to match one of those you have in allowed hosts e.g
ALLOWED_HOSTS = ['localhost',...]
...
.....
response = client.post(url, data, SERVER_NAME='localhost')
I get Successful status code for my POST requests , Login is working fine , but the SMS is not sent
I have gone through all codes on internet, most of them are out-dated, as the site has changed its code.
import requests as req
def login_way2sms():
with req.Session() as mySession:
url = 'http://www.way2sms.com/re-login'
home_url = 'http://www.way2sms.com/'
mobile = [your registered mobile number]
password = [your password]
headers = dict(Referrer="http://www.way2sms.com/")
before = mySession.get(home_url)
login_data = dict(mobileNo=mobile, password=password, CatType='', redirectPage='', pid='')
mySession.post(url, data=login_data, headers=headers)
after = mySession.get(home_url)
return mySession
def send_msg(mysession): #saw sendsms-toss in Inspect under Network tab
url = 'http://www.way2sms.com/smstoss'
home_url = 'http://www.way2sms.com/'
sms_url = 'http://www.way2sms.com/send-sms'
group_contact_url = 'http://www.way2sms.com/GroupContacts'
web_msg_count_url = 'http://www.way2sms.com/CheckWebMsgCount'
headers = dict(Referrer="http://www.way2sms.com/send-sms")
before = mysession.get(home_url)
token = '2B7CF7C9D2F14935795B08DAD1729ACF'
message = 'How to make this work?'
mobile = '[a valid phone number]'
ssaction = 'undefined'
senderid = 'WAYSMS'
msg_data = dict(Token=token, message=message, toMobile=mobile, ssaction=ssaction, senderId=senderid)
mysession.post(url, data=msg_data, headers=headers)
after = mysession.get(home_url)
mysession.post(group_contact_url, headers=headers)
group_contacts = mysession.get(sms_url)
mysession.post(web_msg_count_url, headers=headers)
web_msg_count = mysession.get(sms_url)
# last 2 POST requests send after clicking the Send Msg button
def main():
login_way2sms() #login using username and password
send_msg(currsession) #send sms
main()
I finally got it right , Thanks for replying. We can do it without using the apikey and secret keys as well, Here take a look at this. And init is just another script where constant urls and login is defined, nothing much there.
import requests as req
import init
def login_way2sms(credential):
with req.Session() as mySession:
mobile = credential.username
password = credential.password
headers = dict(Referrer="http://www.way2sms.com/")
login_data = dict(mobileNo=mobile, password=password, CatType='', redirectPage='', pid='')
mySession.post(init.login_url, data=login_data, headers=headers)
return mySession
def get_token(mysession):
cookies = mysession.cookies['JSESSIONID']
token = cookies[4:]
return token
def send_msg(mysession, token):
"""
:rtype: req.Session()
"""
headers = dict(Referrer="http://www.way2sms.com/send-sms")
message = 'Hi, I am Upgraded a little!!!'
mobile = '[valid phone]'
msg_data = dict(Token=token, message=message, toMobile=mobile, ssaction=init.ssaction, senderId=init.senderid)
mysession.post(init.sms_url, data=msg_data, headers=headers)
def main():
credential = init.enter_credentials()
currsession = login_way2sms(credential)
reply = currsession.get(init.home_url)
page_content: str = str(reply.content)
if (reply.status_code == 200) and (page_content.find('send-sms', 10, 200) != -1):
print("Login Successful!\n")
else:
print("Login Failed , Try again\n")
credential = init.enter_credentials()
currsession = login_way2sms(credential)
token = get_token(currsession)
send_msg(currsession, token)
main()
The following method and code worked for me after creating a free account at way2sms (I hope you already did it). Then click on API tab then campaign at left. Then create test API and Secret Key (free with 25 message limit). Then use the following code--
import requests
import json
URL = 'http://www.way2sms.com/api/v1/sendCampaign'
# get request
def sendPostRequest(reqUrl, apiKey, secretKey, useType, phoneNo, senderId, textMessage):
req_params = {
'apikey':'your_apiKey',
'secret':'your_secretKey',
'usetype':'stage'
'phone': 'receiving_phone_number',
'message':'The textMessage I want to send',
'senderid':'Your Name'
}
return requests.post(reqUrl, req_params)
# get response
response = sendPostRequest(URL, 'provided-api-key', 'provided-secret', 'prod/stage', 'valid-to-mobile', 'active-sender-id', 'message-text' )
"""
Note:-
you must provide apikey, secretkey, usetype, mobile, senderid and message values
and then requst to api
"""
# print response if you want
print response.text
Just fill the fields and run in python 2.7. Working perfectly on any Indian number.
Okay so I'm using code very similar to this (https://gist.github.com/metadaddy-sfdc/1374762)
to get authentication token and do simple query's using the libur2 for the rest api in python for a sales force database, but when I tried to follow the instructions which were given in this answer How to make HTTP DELETE method using urllib2?,
I cannot get it to work so that I can use delete, both codes use liburl but they seem to be in different format, so that I don't know how to apply the solution offered on stack exchange, to my code, as you can tell I am a beginner so any help would be greatly appreciated
edit:
here is the code I'm using with keys/passwords blanked
import urllib
import urllib2
import json
import pprint
import re
import subprocess
def authorise():
consumer_key = '**********************'
consumer_secret = '**************'
username = '***********'
password = '*****************'
login_server = 'https://login.salesforce.com'
token_url = login_server+'/services/oauth2/token'
params = urllib.urlencode({
'grant_type': 'password',
'client_id': consumer_key,
'client_secret': consumer_secret,
'username': username,
'password': password
})
data = urllib2.urlopen(token_url, params).read()
oauth = json.loads(data)
return oauth
def country_id_query(params):
query_url = oauth['instance_url']+'/services/data/v23.0/query?%s' % params
headers = {
'Authorization': 'OAuth '+oauth['access_token']
}
req = urllib2.Request(query_url, None, headers)
data = urllib2.urlopen(req).read()
result = json.loads(data)
id = result['records'][0]['Id']
return id
oauth = authorise()
token = oauth['access_token']
print "\ntoken is = " + token
params = urllib.urlencode({
'q': 'SELECT id from Country__c WHERE name = \'A New Found Land\''
})
id = country_id_query(params)
print "\nCountry id is "+id + "\n"
I am looking to find out what I need to add to this to get DELETE working
Okay, found the solution to above for anyone with a similar problem:
def delete_country(id):
query_url = oauth['instance_url']+'/services/data/v23.0/sobjects/Country__c/%s' % id + '/'
headers = {
'Authorization': 'OAuth '+oauth['access_token']
}
opener = urllib2.build_opener(urllib2.HTTPHandler)
req = urllib2.Request(query_url, None, headers)
req.get_method = lambda: 'DELETE' # creates the delete method
url = urllib2.urlopen(req) # deletes database item