How to send data from python client to Django web server? - python

I'd like python3 program to send JSON data to Django web server and print them on web page. This is what I have in Views.py:
def receive_json(request):
if request.method == 'POST':
received_data = json.loads(request.body.decode("utf-8"))
return StreamingHttpResponse('it was post request: ' + str(received_data))
return StreamingHttpResponse('it was get request')
And the python code:
import requests
import json
url = "http://127.0.0.1:8000/"
data = {"data": [{'key1':'val1'}, {'key2':'val2'}]}
headers = {'content-type':'application/json'}
r = requests.post(url, data=json.dumps(data), headers=headers)
r.text
However, it shows this message:
Forbidden (CSRF cookie not set.): /
[28/May/2021 16:51:31] "POST / HTTP/1.1" 403 2864

import requests
import json
url = "http://127.0.0.1:8000/"
data = {"data": [{'key1':'val1'}, {'key2':'val2'}]}
headers = {'content-type':'application/json','Cookie':'csrftoken=axXsa39e5hq8gqlTjJFHAbUWtg2FQgnSd3cxxkx9khatqgersthtSryDxtF0cVCk'}
r = requests.post(url, data=json.dumps(data), headers=headers)
r.text
i think these may works by adding Cookie but it would be better if u use #csrf_exempt decorater in receive_json function by these way
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def receive_json(request):
if request.method == 'POST':
received_data = json.loads(request.body.decode("utf-8"))
return StreamingHttpResponse('it was post request: ' + str(received_data))
return StreamingHttpResponse('it was get request')

Essentially you need first to perform a GET request to get a csrftoken, than post that together with the data. There are a few ways to do this. Here is one (untested however):
import requests
import json
url = "http://127.0.0.1:8000/"
s = requests.Session()
s.get(url)
headers = {
'content-type':'application/json',
'X-CSRFToken': s.cookies["csrftoken"],
}
data = {"data": [{'key1':'val1'}, {'key2':'val2'}]}
r = s.post(url, data=json.dumps(data), headers=headers)
r.text
You can find more information in Django's CSRF documentation.

Related

FTX API error "Missing parameter accounts"

I hope someone could help me in this.
Following this official doc from FTX:
https://docs.ftx.com/#request-historical-balances-and-positions-snapshot
I'm continue to get this error:
{'success': False, 'error': 'Missing parameter accounts', 'errorCode': 'parameter_missing'}
The code was ok and getting all the response from the other API call until I tested the the one above and I had to add the parameters, those are not working :-(
Here is my code:
import requests
from requests import Request, Session
import time
import hmac
import json
s = requests.Session()
url = "https://ftx.com/api/historical_balances/requests"
ts = int(time.time() * 1000)
tsN = int(time.time())
params = {
"accounts": ["main","subaccounts"],
"endTime": tsN,
}
request = requests.Request("POST", url, params=params)
prepared = request.prepare()
signature_payload = f'{ts}{prepared.method}{prepared.path_url}'.encode()
if prepared.body:
signature_payload += prepared.body
signature = hmac.new('MYSECRET'.encode(), signature_payload, 'sha256').hexdigest()
request.headers = {
'FTX-KEY': 'MYKEY',
'FTX-SIGN': signature,
'FTX-TS': str(ts),
}
r = s.send(request.prepare())
r.json()
print('Output Json :',r.json())
Do you have any suggestion please? I'm getting crazy with this... Thanks!!
Try switching request = requests.Request("POST", url, params=params) to request = requests.Request("POST", url, data=params) or request = requests.Request("POST", url, json=params), because I believe they want you to send them accounts and endTime as body of request, not as url parameters.

Request data from Linkedin

I have Problem with scraping data from LinkedIn.
I think the documentation is too complicated ...
here the problem, I want to make a request (GET) and get for example data of my feed/posts/chats or whatever.
here is my code:
import json
import requests
# URL = "https://www.linkedin.com/voyager/api/voyagerMessagingDashConversationNudges"
URL = "https://www.linkedin.com/voyager/api/identity/dash/profiles"
cookies = {
#Cookies are here
}
params = {
'decorationId': 'com.linkedin.voyager.dash.deco.identity.profile.WebTopCardCore-6',
'memberIdentity': 'maria-albert-137632240',
'q': 'memberIdentity',
}
def get_group(url: str, cookies: dict, data:dict, header: dict):
response = requests.get(url=url, cookies=cookies, data=json.dumps(data), headers=header)
response.raise_for_status()
return response.json()
if __name__ == "__main__":
print("sending request to Server:\n")
get_group(url=URL, cookies=cookies, data=params, header=headers)
but I couldn't do it, the error --> raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: INKApi Error for url: https://www.linkedin.com/voyager/api/identity/dash/profiles
Thanks for your help.
You just need to set header like this:
header = {
"accept": 'application/vnd.linkedin.normalized+json+2.1',
"cookie": 'JSESSIONID="ajax:abcd"; li_at=abcdabcd',
}
and so fill the payload as the endpoint needed.
You don't have to Create App to access token or anything else.

Troubles with python requests lib and redirect in Flask

I try to create a service with Flask that has two functions: 1) Send post request (with python requests lib) with credentials for login on the forum; 2) After success login to open another page from this forum with Flask redirect method.
The code looks as:
#app.route("/protected_area")
#login_is_required
def protected_area():
session = requests.Session()
user = fake_useragent.UserAgent().random
header = CaseInsensitiveDict()
header['user-agent'] = user
payload = {
'mode': MODE,
'username': LOGIN,
'password': PASS
}
print(payload)
url_main = BASIC_SITE_URL + 'login'
url_login = BASIC_SITE_URL + 'login/form'
url_cabinet = BASIC_SITE_URL + '?perspective=pa-home'
response = session.get(url_main, headers=header, allow_redirects=False)
cookies = get_cookies(response.cookies, "tm.domain.com")
print('cookies_1:', cookies)
cookies = cookies.split(';')
print('cookies_2:', cookies)
cookies = [(c.split('=', 1)) for c in cookies]
print('cookies_3:', cookies)
session.cookies.update(dict(cookies))
print('session.cookies:', session.cookies.update(dict(cookies)))
print('dict_cookies:', dict(cookies))
response = session.post(url_login, data=payload, cookies=dict(cookies), headers=header, allow_redirects=False)
print('response:', response)
print(response.text)
if response.status_code == 200:
print('Sucessful!')
return redirect(url_cabinet)
elif response.status_code == 404:
print('Unsuccessful!')
return redirect(url_main)
But it doesn't work: I don't know how to send session/headers to open the page with redirect - this page opens as an unauthorized user.
Is there a reason you're printing out individual cookies and then re-wrapping cookies in another dict? It should be as simple as passing the response cookies to the next request:
...
response = session.get(url_main, headers=header, allow_redirects=False)
...
...
next_response = response = session.post(url_login, data=payload, cookies=response.cookies, headers=header, allow_redirects=False)
...
...

Python post to remote host

Hi I want to write robot to register in toefl test , I send request to remote web site as:
from django.http import HttpResponse
import requests
from bs4 import BeautifulSoup
from django.middleware import csrf
def index(request):
session = requests.Session()
page = session.get('https://toefl-registration.ets.org/TOEFLWeb/extISERLogonPrompt.do')
if request.method == 'POST':
url = 'https://toefl-registration.ets.org/TOEFLWeb/logon.do'
data = {
'password': request.POST.get('password', ''),
'username': request.POST.get('username', ''),
'org.apache.struts.taglib.html.TOKEN': request.POST.get('org.apache.struts.taglib.html.TOKEN', '')
}
page = session.post(url, data=data)
return HttpResponse(request,page.text)
My post request is not same as post request made by toefl original web site and instead of login shows error as : We are sorry, our servers are currently busy. Please wait a few minutes and retry your request.
what is the problem? someone in other corporation did this without error
you should make sure that you enter cookies correctly like:
def index(request):
response = HttpResponse()
if 'JSESSIONID' in request.COOKIES:
print('1')
else:
session = requests.Session()
page = session.get('https://toefl-registration.ets.org/TOEFLWeb/extISERLogonPrompt.do')
cookie = page.cookies
for c in cookie:
response.set_cookie(c.name, c.value)
iud = '1'
if request.method == 'POST':
url = 'https://toefl-registration.ets.org/TOEFLWeb/logon.do'
iud = '2'
page = requests.post(url, data=data, cookies=request.COOKIES)
cookie = page.cookies
response.write(pageReader(request, page.text, iud))
return response

Issue with making transaction in Neo4J Python

I am trying to send a POST request with a Neo4j transaction query. Although I get a response 200 the node is not created. This is my Python script:
import requests
import json
import csv
headers = {'content-type': 'application/json'}
url = "http://localhost:7474/db/data/transaction/commit"
checkNode = {"query" : '{"statements": [{"statement":"CREATE (n:test) RETURN n"}]}'}
mkr =requests.post(url, data=json.dumps(checkNode), headers=headers)
print(mkr)
I haven't used transactions before and nver tried to create one through the Rest Api. What am I doing wrong here?
It seems unlikely to me that you're receiving a response code of 200; you should be getting a 500 as the transactional endpoint doesn't accept a query parameter. Try this:
import requests
import json
import csv
headers = {'content-type': 'application/json'}
url = "http://localhost:7474/db/data/transaction/commit"
checkNode = {"statements":[{"statement":"CREATE n RETURN n"}]}
mkr = requests.post(url, data=json.dumps(checkNode), headers=headers)
print(mkr.text)

Categories

Resources