Python - Request check? - python

POSTURL = 'https://partner.spreadshirt.de/login'
REQURL = 'https://partner.spreadshirt.de/dashboard'
payload = {
"username": 'test#gmail.com',
"password": 'somepassword'
}
import requests
with requests.Session() as session:
post = session.post(POSTURL, data=payload)
r = session.get(REQURL)
print("String" in r.text)
I know that this String is in present on the Website so this is not the problem. But my code returns False, so maybe I cant get to the REQURL? How could I determine if I got there?

Related

Call API with Python using Token

I am trying to call an API using an access token.
Currently I am getting the token like so:
import requests
auth_url = "https://oauth.thegivenurl.com/connect/token"
client_id = "SomeClient_ID"
client_secret = "SomeClient_Secret"
scope = "SomeScope"
grant_type = "client_credentials"
data = {
"grant_type": grant_type,
"client_id": client_id,
"client_secret": client_secret,
"scope": scope
}
auth_response = requests.post(auth_url, data=data)
print(auth_response.content)
This produces something like the following:
{"access_token":"eyJhbGdiOihSUzh1NhIsImtpZCI6IjlVUHVwYnBkTXN2RDZ0Ry1ZcDVRUlEiLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE2MzM4OTcxNDIsImV4cCI6hTYzMhkwMDc0MiwiaXNzIjoiaHR0cHM6Ly9vYXV0aC56YW1iaW9uLmNvbSIsImF1ZCI6ImFwaTEiLCJjbGllbnRfaWQiOiIwN0I3RkZEOC1GMDJCLTRERDAtODY2OS0zRURBNzUyRTMyNkQiLCJzY29wZSI6WyJhcGkxIl19.GU6lynvQYAAmycEPKbLgHE-Ck189x-a-rVz6QojkBIVpSLu_sSAX2I19-GlTjVWeLKoMVxqEfVq_qIaaQYa5KFmMLHRxP6J-RUgGK8f_APKjX2VNoMyGyAbZ0qXAJCvUTh4CPaRbZ6pexEishzr4-w3JN-hJLiv3-QH2y_JZ_V_KoAyu8ANupIog-Hdg8coI3wyh86OeOSAWJA1AdkK5kcuwC890n60YVOWqmUiAwPRQrTGh2mnflho2O3EZGkHiRPsiJgjowheD9_Wi6AZO0kplHiJHvbuq1PV6lwDddoSdAIKkDscB0AF53sYlgJlugVbtU0gdbXjdyBZvUjWBgw","expires_in":3600,"token_type":"Bearer","scope":"api1"}
Now I would like to call the API and pass the token in a header, but I am unsure how to do this and I have had a couple of goes at online resources
One of my attempts were:
url = "https://anotherurl.com/api/SecuredApi/StaffDetails"
head = {'Authorization': 'token {}'.format(auth_response)}
response = requests.get(url, headers=head)
print(response)
but this gives me a 403 error
Please assist me with pointing out my error
EDIT:
Thanks to #RaniSharim I have made some changes. I now have
import requests
import json
auth_url = "https://oauth.thegivenurl.com/connect/token"
client_id = "SomeClient_ID"
client_secret = "SomeClient_Secret"
scope = "SomeScope"
grant_type = "client_credentials"
data = {
"grant_type": grant_type,
"client_id": client_id,
"client_secret": client_secret,
"scope": scope
}
dateparams = {
"StartDateTime": "2021-01-01 00:00:00",
"EndDateTime" : "2021-10-11 23:59:00"
}
auth_response = requests.post(auth_url, data=data)
# print(auth_response.content)
authjson = auth_response.content
authdata = json.loads(authjson)
token = (authdata['access_token'])
# print(token)
head = {"Authorization": "Bearer " + token}
response = requests.get(url, headers=head, params=dateparams)
print(response.content)
This looks better but I am now getting a 400 error:
"message":"The date range you have specified is in an invalid format. The required format is yyyy-MM-dd HH:mm:ss","status":400}
As best I can see my date ranges are already in the requested format, as set here:
dateparams = {
"StartDateTime": "2021-01-01 00:00:00",
"EndDateTime" : "2021-10-11 23:59:00"
}
Normally, 400 means front-end error, but when you do GET request
dateparams = {
"StartDateTime": "2021-01-01 00:00:00",
}
r = requests.get(url, params=dateparams)
print(r.url)
GET url will turn into sth like this:
https://oauth.thegivenurl.com/connect/token?StartDateTime=2021-01-01+00%3A00%3A00
see the str
2021-01-01+00%3A00%3A00
So if back-end can't handle this right, you'll get this error too
but you can use GET in another way:
requests.get(url, json=dateparams)
This will send your json params perfectly

Logging in to Magento account from Python script

I'm trying to login to Magento account from Python script using requests module, the relevant code I made looks as below:
s = requests.session()
main_url = '<redacted.tld>/en/index.html'
html_data = s.get('https://'+main_url, headers=headers, timeout=(30, 30), verify=dst_verify_ssl)
web_user = 'test#test.com'
web_pass = '123test321'
form_key = soup.find('input', {'name':'form_key'})['value']
l_url = 'https://<redacted.tld>/'
l_route = 'en/customer/account/loginPost/'
login_payload = {
'form_key':form_key,
'login[username]':web_user,
'login[password]':web_pass
}
login_req = s.post(l_url + l_route, headers=headers, data=login_payload)
But it's not getting me logged in so I was wondering if someone could tell me what does it take to login via Python to the Magento account?
Thanks.
I gave this one a go on a public demo instance and I can see the data on the Magento 2 dashboard just fine:
import requests
from bs4 import BeautifulSoup
web_user = 'youremail#example.com'
web_pass = 'yourpassword'
s = requests.session()
main_url = 'https://magento2demo/'
html_data = s.get(main_url)
form_soup = BeautifulSoup(html_data.content, 'html.parser')
form_key = form_soup.find('input', {'name':'form_key'})['value']
login_route = 'https://magento2demo/customer/account/loginPost/'
login_payload = {
'form_key': form_key,
'login[username]': web_user,
'login[password]': web_pass
}
login_req = s.post(login_route, data=login_payload)
account_url = "https://magento2demo/customer/account/"
html_account = s.get(account_url)
account_soup = BeautifulSoup(html_account.content, 'html.parser')
info = account_soup.find('div', {'class':'box-information'}).find('div', {'class':'box-content'})
assert web_user in str(info)
"beautifulsoup4": { "version": "==4.9.3"
"requests": { "version": "==2.26.0"
What's the response code on the POST? Anything peculiar in your headers?
Might wanna add more reproducible data if the above doesn't help.

How can I send this request using python requests library

How to send the below request using python requests library?
Request :
I have tried
with requests.Session() as session:
// Some login action
url = f'http://somewebsite.com/lib/ajax/service.php?key={key}&info=get_enrolled'
json_data = {
"index": 0,
"methodname": "get_enrolled",
// And so on, from Request Body
}
r = session.post(url, json=json_data)
But it doesn't give the output I want.
1.Define a POST request method
import urllib3
import urllib.parse
def request_with_url(url_str, parameters=None):
"""
https://urllib3.readthedocs.io/en/latest/user-guide.html
"""
http = urllib3.PoolManager()
response = http.request("POST",
url_str,
headers={
'Content-Type' : 'application/json'
},
body=parameters)
resp_data = str(response.data, encoding="utf-8")
return resp_data
2.Call the function with your specific url and parameters
json_data = {
"index": 0,
"methodname": "get_enrolled",
// And so on, from Request Body
}
key = "123456"
url = "http://somewebsite.com/lib/ajax/service.php?key={0}&info=get_enrolled".format(key)
request_with_url(url, json_data)
With no more info what you want and from what url it is hard to help but.
But try adding headers with the user-agent to the post. More headers may be needed, but User-Agent is a header that is often required.
with requests.Session() as session:
// Some login action
url = f'http://somewebsite.com/lib/ajax/service.php?key={key}&info=get_enrolled'
json_data = {
"index": 0,
"methodname": "get_enrolled",
// And so on, from Request Body
}
headers = {'User-Agent': 'Mozilla/5.0'}
r = session.post(url, json=json_data, headers=headers)

Does Robinhood still support its API?

Does Robinhood still support its API. I keep getting a login failed error. Here's what I tried:
import requests
def login():
u = "myusername"
p = "mypassword"
url = "https://api.robinhood.com/api-token-auth/"
data = {"username": u, "password": p}
r = requests.post(url, json=data)
return r.text
print login()
I also unsuccessfully tried most of the "Python API Wrappers" on Github.
Give this a try:
import requests
def login():
username = 'username'
password = 'password'
header = {"Accept": "application/json"}
data = {"client_id": "c82SH0WZOsabOXGP2sxqcj34FxkvfnWRZBKlBjFS",
"expires_in": 86400,
"grant_type": "password",
"password": "pword",
"scope": "internal",
"username": "uname"}
url = "https://api.robinhood.com/oauth2/token/"
r = requests.post(url, data=data, headers=header)
return r.text
print(login())

Update Sharepoint 2013 using Python3

I am currently trying to update a Sharepoint 2013 list.
This is the module that I am using using to accomplish that task. However, when I run the post task I receive the following error:
"b'{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"Invalid JSON. A token was not recognized in the JSON content."}}}'"
Any idea of what I am doing wrong?
def update_item(sharepoint_user, sharepoint_password, ad_domain, site_url, sharepoint_listname):
login_user = ad_domain + '\\' + sharepoint_user
auth = HttpNtlmAuth(login_user, sharepoint_password)
sharepoint_url = site_url + '/_api/web/'
sharepoint_contextinfo_url = site_url + '/_api/contextinfo'
headers = {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'odata': 'verbose',
'X-RequestForceAuthentication': 'true'
}
r = requests.post(sharepoint_contextinfo_url, auth=auth, headers=headers, verify=False)
form_digest_value = r.json()['d']['GetContextWebInformation']['FormDigestValue']
item_id = 4991 # This id is one of the Ids returned by the code above
api_page = sharepoint_url + "lists/GetByTitle('%s')/items(%d)" % (sharepoint_listname, item_id)
update_headers = {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose",
"odata": "verbose",
"X-RequestForceAuthentication": "true",
"X-RequestDigest": form_digest_value,
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
}
r = requests.post(api_page, {'__metadata': {'type': 'SP.Data.TestListItem'}, 'Title': 'TestUpdated'}, auth=auth, headers=update_headers, verify=False)
if r.status_code == 204:
print(str('Updated'))
else:
print(str(r.status_code))
I used your code for my scenario and fixed the problem.
I also faced the same problem. I think the way that data passed for update is not correct
Pass like below:
json_data = {
"__metadata": { "type": "SP.Data.TasksListItem" },
"Title": "updated title from Python"
}
and pass json_data to requests like below:
r= requests.post(api_page, json.dumps(json_data), auth=auth, headers=update_headers, verify=False).text
Note: I used SP.Data.TasksListItem as it is my type. Use http://SharePointurl/_api/web/lists/getbytitle('name')/ListItemEntityTypeFullName to find the type

Categories