Python not able to put a variable in header "session-token" - python

i'm working on winrest api and since my session token will change from time to time i would like to ad it in a variable, when run my code i get a return request('get', url, params=params, **kwargs)
here the code :
sessionToken = 'session_token': 'gggg6gsl68l2vdim5fgggggg'}
headers = {
'App-Token': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'Session-Token': sessionToken
}
response = requests.get(urlUnencryptedWorkstation, headers=headers)

I believe this is what you're looking for:
import requests as req
urlUnencryptedWorkstation = 'https://www.google.com' # Whatever the url is
sessionToken = 'gggg6gsl68l2vdim5fgggggg'
headers = {
'App-Token': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'Session-Token': sessionToken
}
res = req.get(urlUnencryptedWorkstation, headers=headers)
print(res.status_code, res.text)
Hope this helps :) Cheers!

Related

How to run a function in the background of flask app

I have a web application route in flask. The route is supposed to give the user an analysis of their data after 30 minutes. To do this, they initiate the route. This triggers an API request that takes gets their initial data. The route then sleeps for 30 minutes, and then triggers the same exact API response. The initial data is subtracted from the final data and result the data that is 'attained' in that 30 minutes and is upserted to a database. An example of how it would look is below. I would like my users to be able to use the other features of the website, or more importantly even initiate another instance of this function, while this runs. My question is: is this an async problem or a multithread problem and why? I would like to note that my question is more conceptual then about the actual code.
#app.route("/data/", methods=['GET', 'POST', 'UPDATE'])
#login_required
def data():
Url = "https://data-api.com"
payload={}
headers = {
'Authorization': AUTH
}
response = requests.request("GET", Url, headers=headers, data=payload)
data_json = json.loads(response.text)
data1_init = data_json["a"]["b"]["c"]
data2_init = data_json["e"]["f"]["g"]
data3_init = data_json["h"]["i"]["j"]
sleep(1800)
Url = "https://data-api.com"
payload={}
headers = {
'Authorization': AUTH
}
response = requests.request("GET", Url, headers=headers, data=payload)
data_json = json.loads(response.text)
data1_final = data_json["a"]["b"]["c"]
data2_final = data_json["e"]["f"]["g"]
data3_final = data_json["h"]["i"]["j"]
data1 = data1_final - data1_initial
data2 = data2_final - data2_initial
data3 = data3_final - data3_initial
data_info = DBModel(data1=data1, data2=data2, data3=data3)
db.session.commit()
return render_template('loading.html')
def run_func():
data = { 'some': 'data', 'any': 'data' }
thr = Thread(target= *your_function*, args=[app, data])
thr.start()
return thr
You can use threading. Put your function name in place of "your_function", pass the function parameters in args and there you go. Just call the run_func() wherever you want to execute and it starts running in background in an other thread.

Sending documents with python and Telegram

I'm trying to send documents via Telegram API but I'm getting an error.
The class I have created is the following:
def sendDocument(self):
url = self.url + '/sendDocument'
fPath = 'C:/Users/users/user/OneDrive - Personal/syslog.txt'
params = {
'chat_id': self.chat_id,
'document': open(fPath, 'rb')
}
resp = requests.post(url, params=params)
if resp.status_code != 200: print('Status: ', resp.status_code)
I have relied on documentation I have found on the internet, as well as on the class I have already created and IT DOES WORK, to send text messages:
def sendMessage(self, text):
url = self.url + '/sendMessage'
params = {
'chat_id': self.chat_id,
'text': text,
'parse_mode': 'HTML'
}
resp = requests.post(url, params=params).
if resp.status_code != 200: print('Status: ', resp.status_code)
Could someone help me understand where the error is? Thank you very much!
The params adds query parameters to url, and it's impossible to send files this way. To send files with the requests library, you should use files parameter:
def sendDocument(self):
url = self.url + '/sendDocument'
fPath = 'C:/Users/users/user/OneDrive - Personal/syslog.txt'
params = {
'chat_id': self.chat_id,
}
files = {
'document': open(fPath, 'rb'),
}
resp = requests.post(url, params=params, files=files)
...
I think you should share file name in prams like below:
c_id = '000011'
filename = '/tmp/googledoc.docx'
context.bot.send_document(chat_id='c_id', document=open('googledoc.docx', 'rb'), filename="googledoc.docx")

my python requests return 401 while postman returns 200

i make my requests class, the code is as below:
class RunMethod:
def post_main(self, url, data, header=None):
res = None
if header != None:
res = requests.post(url=url, data=data, headers=header)
else:
res = requests.post(url=url, data=data)
return res.json()
def get_main(self, url, data=None,header=None):
res = None
if header != None:
res = requests.get(url=url,data=data,headers=header,verify=False)
else:
res = requests.get(url=url,data=data,verify=False)
return res.json()
def run_main(self, method,url,data=None,headers=None):
res = None
if method == 'get':
res = self.get_main(url, data, headers)
else:
res = self.post_main(url, data, headers)
and i capture an api from charles and test it in postman, it returns 200. i export python code from postman and it is like this:
import requests
url = "https://stargate.ar.elenet.me/minimart.service/intelligent/invoke"
querystring = {"traceId": "1000000294010",
"shelfCode": "lu8ssMgCpgq00FDYdpX76Q..", "tracedAt": "1545641563164"}
payload = ""
headers = {
'X-STARGATE-ACCESS-TOKEN': "d7594351-0663-43a8-ad55-180c8b29db82",
'Cookie': "SID=NTVMAu8FKskyj06ln8J9uhS45fgcRNk1V3jQ; USERID=2228440841",
'Authorization': "ElemeAPI token",
'cache-control': "no-cache"
}
response = requests.request(
"GET", url, data=payload, headers=headers, params=querystring)
print(response.text)
it works, and i changed my class, put the data like this:
url = "https://stargate.ar.elenet.me/minimart.service/intelligent/invoke?traceId=1000000294010&shelfCode=lu8ssMgCpgq00FDYdpX76Q..&tracedAt=1545641563164"
headers = {
'X-STARGATE-ACCESS-TOKEN': "d7594351-0663-43a8-ad55-180c8b29db82",
'Cookie': "SID=NTVMAu8FKskyj06ln8J9uhS45fgcRNk1V3jQ; USERID=2228440841",
'Authorization': "ElemeAPI token",
'cache-control': "no-cache",
'Content-Type':'application/json'
}
exam = RunMethod()
res = exam.run_main('get', url, headers)
i just put querystring into url, but it returns 401.
i don't know where it's wrong. could anybody help me? thanks a lot!
Update your code in get_main method as per below code.
res = requests.get(url=url,params=data,headers=header,verify=False)
Here we are calling instantiated RunMethod class and calling run_main method.
exam = RunMethod()
res = exam.run_main('get', url, querystring, headers)
The run_main accepts 4 arguments, exam.run_main('get', url, headers) provides only 3 of them (method='get', url=url, data=headers, headers=None).
I would recommend to use named arguments when skipping some of the optional ones:
exam.run_main('get', url, headers=headers)

How to read the next page on API using python?

I need help on how to do a loop so each time I make a GET request, it will always be the new page from the API.
I start with getting the first response. It includes a parameter to the next page next_key
{
"result": [
{
...,
...
}
],
"next_key": 123
}
Below is my current attempt
import requests
import json
url = "https://flespi.io/gw/channels/all/messages"
headers = {"Authorization": "FlespiToken 23ggh45"}
def getFirst():
data = {"limit_count":100, "limit_size":10000}
params = {"data":json.dumps(data, separators=(",", ":"))}
reqFirst = requests.get(url, params=params, headers=headers).json()
return reqFirst["next_key"] ## this returns "123"
def getDataNext():
data = {"limit_count":100, "limit_size":10000, "curr_key":getFirst()}
params = {"data":json.dumps(data, separators=(",", ":"))}
reqNext = requests.get(url, params=params, headers=headers)
jsonData = reqNext.json()
while True:
if "next_key" in jsonData:
data = {"limit_count":100, "limit_size":10000,"curr_key":jsonData["next_key"]}
params = {"data":json.dumps(data, separators=(",", ":"))}
req = requests.get(url, params=params, headers=headers).json() ## this should do GET request for the third page and so on...
print req["next_key"] # this returns "3321" which is the value for "next_key" in second page
else:
pass
getDataNext()
The full url including limit count, limit size and curr key is as follows https://flespi.io/gw/channels/all/messages?data=%7B%22curr_key%22%123%2C%22limit_count%22%3A100%2C%22limit_size%22%3A10000%7D
As you can see this only returns the second page that is jsonData["next_key"]. What I want to do is that for each GET request, the program will read the next_key and put it on the next GET request.
I am thinking to use increment on the curr_key but the key is random and also I do not know how many page there is.
I believe there must be just a simple solution for this but apparently I could not think about it. Thank you for your help and suggestion.
try this
has_next_key = False
nextKey = ""
if "next_key" in jsonData:
has_next_key = True
nextKey = jsonData["next_key"]
while has_next_key:
data = {"limit_count":100, "limit_size":10000,"curr_key":nextKey}
params = {"data":json.dumps(data, separators=(",", ":"))}
req = requests.get(url, params=params, headers=headers).json() ## this should do GET request for the third page and so on...
if "next_key" in req:
nextKey = req["next_key"]
print nextKey # this returns "3321" which is the value for "next_key" in second page
else:
has_next_key = False
# no next_key, stop the loop

Python 301 POST

So basically I'm trying to make a request to this website - https://panel.talonro.com/login/ which is supposed to be 301 redirect.
I send data as I should but in the end there is no Location header in my request and status code is 200 instead of 301.
I can't figure out what I am doing wrong. Please help
def do_request():
req = requests.get('https://panel.talonro.com/login/').text
soup = BeautifulSoup(req, 'html.parser')
csrf = soup.find('input', {'name':'csrfKey'}).get('value')
ref = soup.find('input', {'name':'ref'}).get('value')
post_data = {
'auth':'mylogin',
'password':'mypassword',
'login__standard_submitted':'1',
'csrfKey':csrf,
'ref':ref,
'submit':'Go'
}
post = requests.post(url = 'https://forum.talonro.com/login/', data = post_data, headers = {'referer':'https://panel.talonro.com/login/'})
Right now push_data is in do_request(), so you cannot access it outside of that function.
Instead, try this where you return that info and then pass it in:
import requests
from bs4 import BeautifulSoup
def do_request():
req = requests.get('https://panel.talonro.com/login/').text
soup = BeautifulSoup(req, 'html.parser')
csrf = soup.find('input', {'name':'csrfKey'}).get('value')
ref = soup.find('input', {'name':'ref'}).get('value')
post_data = {
'auth':'mylogin',
'password':'mypassword',
'login__standard_submitted':'1',
'csrfKey':csrf,
'ref':ref,
'submit':'Go'
}
return post_data
post = requests.post(url = 'https://forum.talonro.com/login/', data = do_request(), headers = {'referer':'https://panel.talonro.com/login/'})

Categories

Resources