Hellos firends,
I have REST service in Python Django application. I am trying to store some values in the request session post successful login service call.
like the following
request.session['valid']=True
and the I am able to check that the values set properly.
The in the next request when I am trying to retrieve the value I am not able to find any of the keys I had stored.
following is the code to retrieve the keys
if 'valid' not in request.session:
print('Invalid request. . .')
return False
elif request.session['valid']==True:
username=request.session['username']
print('Request validated. . .')
return True
I have the frontend app running on React and Backend REST is on DRF. After the login is done on the following code,
#csrf_exempt
#api_view(['POST'])
def login_details(request):
if request.method == 'POST':
headers = {
'Content-type': 'application/json',
}
# Assuming at this point login is successful, so I am setting the session
request.session['username']=TF_VAR_user_name
request=initSession(request)
data = txt
response = requests.post('https://hooks.slack.com/services/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', headers=headers, data=data)
print(response)
return Response(data_json)
except cx_Oracle.DatabaseError as exc:
error, = exc.args
m = error.message
err="Oracle-Error-Message: "+ str(error.code) + " Oracle-Error-Message: "+error.message
dic2={"Oracle-Error-Code":str(error.code),"Oracle-Error-Message":error.message}
print(dic2)
m=json.dumps(dic2)
n=json.loads(m)
txt="{'text':'User "+atp_userid+" Oracle-Error-Message: "+error.message+"'}"
data = txt
response = requests.post('https://hooks.slack.com/services/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', headers=headers, data=data)
return Response(n)
else:
return Response({ "message":"Unauthoried, please login."},status=status.HTTP_401_UNAUTHORIZED)
The I am trying to read Stored values in the following code,
#csrf_exempt
#api_view(['POST'])
def dashboard(request):
if 'valid' not in request.session:
print('Invalid request. . .')
elif request.session['valid']==True:
username=request.session['username']
print('Request validated. . .')
Please help me how can store values in session and retrieve in the subsequent request. I am sorry for the trouble as I am completely new to Python and Django
Related
Using a simple Python script, i want to send a request, with Python-Requests, to a Django view. The Django view should receive the json data inside the request and should print it to my console; here is what i tried:
This is how i send the request:
url = 'http://127.0.0.1:8000/myview/view'
client = requests.session()
csrftoken = requests.get(url).cookies['csrftoken']
data = json.dumps({'data': 'test-value'})
header = {'X-CSRFToken': csrftoken}
cookies = {'csrftoken': csrftoken}
resp = requests.post(url, data=data, headers=header, cookies=cookies)
And this is how the Django view receives it:
def myview(request):
if request.method == 'POST':
data = request.POST.get('data')
print(data)
print('received.')
response = HttpResponse(get_token(request))
return response
The problem with my current code is that print(data) will throw the following output:
None
received.
[06/Jan/2020 21:23:57] "POST /myview/view HTTP/1.1" 200 64
So, instead of printing test-value, it prints nothing. I don't understand whether the error is in my Django view or in how i'm sending the request. Any advice is appreciated!
The problem is with your request, and entirely caused by this line:
data = json.dumps({'data': 'test-value'})
You simply want
data = {'data': 'test-value'}
The POST data should be sent as a simple dictionary, not a JSON string - see the documentation and example here.
I am creating an app for use in our organization that will login users based on their Office 365 credentials using OAuth2.0. I am fetching an access token that I will store in a session variable. Here is an example of what I am doing:
#never_cache
def authorization(request):
microsoft = OAuth2Session(client_id,scope=scope,redirect_uri=redirect_uri)
token = ""
try:
users = 'https://graph.microsoft.com/v1.0/me' ##msgraph query url-
##This query is purelyjust used to
##authenticate user!
token = microsoft.fetch_token(token_url,client_secret=client_secret,code=request.GET.get('code', '')) ##Code is the authorization code present
##in request URL
header = {'Authorization': 'Bearer ' + token['access_token']}
response = requests.get(url = users, headers = header)
if int(response.status_code) != 200: ##if status code is not 200, then authentication failed. Redirect to login.
print ('Not validated. Return to login.')
request.session.flush()
return redirect('http://localhost:8000/login')
except Exception as e:
print ('User not does not have authentication rights')
request.session.flush()
return redirect('http://localhost:8000/login')
request.session['oauth_state'] = 'authorized'
response = HttpResponseRedirect('http://localhost:8000/search')
return response
I am then using this to check if 'oauth_state' is set to 'authorized'. However, I may change this so that the token is used to query the MS Graph API in each function in order to check if the user has proper permissions or not. Here's an example of what I am doing:
def search(request):
try:
if (str(request.session['oauth_state']) != 'authorized'):
print ('Not authorized')
request.session.flush()
return redirect('http://localhost:8000/login')
except Exception as e:
print ('Not authorized')
request.session.flush()
return redirect('http://localhost:8000/login')
<rest of code>
How insecure is this? Should I possibly be passing in the token to the response header? Or should I get rid of this method, and use django's standard auth and login system? I really appreciated the benefits of OAuth2.0, but if this method compromises our security, I might scrap it.
so I am hosting an image using flask and then I want to do a post request to an API using the url all in the same code:
#app.route('/host')
def host():
return send_from_directory("C:/images", "image1.png")
#app.route('/post')
def post():
response = requests.post(url, data={'input':'<url for host>', headers=headers)
return jsonify(response.json())
I believe as both these view functions are in the same python file, post() gets blocked.
Is there a workaround this problem ?
PS: if I host images on a different machine, it works, but that's not what I desire.
Thanks!
I think there are some problems with your code.
First, I don't believe there is an #app.post() decorator in Flask. My guess is that you were trying to specify that that route should be POSTed to by your users. The way to do that would be #app.route('/post', methods=['POST']).
Next, it seems like you want the /post endpoint to send a POST request to a user-specified(?) URL when the user sends an HTTP request to this endpoint. The way you would do that for a user-specified / user-POSTed URL is something like this (I haven't run this code to test it):
#app.route('/send_post_request', methods=['POST'])
def send_post_request():
user_posted_data = json.loads(request.data)
user_specified_url = user_posted_data['url']
dict_to_post= { 'input': url_for('hosts') }
headers = {} # Fill these in
response = requests.post(user_specified_url , json=dict_to_post, headers=headers)
return jsonify(response.json())
If the URL to send the POST request to is known by the server, you could have your user simply send a GET request:
#app.route('/send_post_request', methods=['GET'])
def send_post_request():
dict_to_post = { 'input': url_for('hosts') }
headers = {} # Fill these in
server_specified_url = '' # Fill this in
response = requests.post(server_specified_url, json=dict_to_post, headers=headers)
return jsonify(response.json())
I have been using this function to handle http requests with no problems:
def do_request(self, method, url, **kwargs):
params = kwargs.get('params', None)
headers = kwargs.get('headers', None)
payload = kwargs.get('data', None)
request_method = {'GET':requests.get, 'POST': requests.post, 'PUT': requests.put, 'DELETE': requests.delete}
request_url = url
req = request_method[method]
try:
res = req(request_url, headers=headers, params=params, data=json.dumps(payload))
except (requests.exceptions.ConnectionError, requests.exceptions.RequestException) as e:
data = {'has_error':True, 'error_message':e.message}
return data
try:
data = res.json()
data.update({'has_error':False, 'error_message':''})
except ValueError as e:
msg = "Cannot read response, %s" %(e.message)
data = {'has_error':True, 'error_message':msg}
if not res.ok:
msg = "Response not ok"
data.update({'has_error':True, 'error_message':msg})
if res.status_code >= 400:
msg = 'Error code: ' + str(res.status_code) + '\n' + data['errorCode']
data.update({'has_error':True, 'error_message': msg})
return data
When I have to do a DELETE request without body entity I have no problems but when I try to add one (when required by the server) I get an error message from the server telling that the body cannot be null as if no body has been sent. Any ideas why this might be happening? I'm using requests module and python 2.7.12. As far as I know data can be send in a DELETE request. Thanks!
There are problems with some clients and some servers when DELETE includes entity body: Is an entity body allowed for an HTTP DELETE request? for example & lots of search results.
Some servers (apparently) convert the DELETE into a POST, others simply perform the DELETE but drop the body. In your case, you've investigated that indeed, the body of a DELETE is dropped by the server & it has been suggested that you change the DELETE to POST.
Mmm... I can send a DELETE with body with Postman and works OK. But I cant get the same result with Requests 2.17.3
This is a issue related to Requests
I have a Django custom URL which works fine in POSTMAN but not working properly in a browser the details are given as below.
In postman, I am using the following URL and it s working fine
127.0.0.1:8000/v0/call_letter_status/
and I am getting a 200 response and output as well
But when I am trying in browser I am getting an error like this
ValueError at /v0/call_letter_status/
The view project.views.User.call_letter_track didn't return an HttpResponse object.
Request Method: GET
Request URL: http://127.0.0.1:8000/v0/call_letter_status/
Django Version: 1.5
Exception Type: ValueError
My Code is as given below:
def call_letter_track(request):
if request.META["CONTENT_TYPE"] == 'application/json':
if request.method == 'GET':
sqlQuery = """ SELECT jc.company_name,jc.job_position,jc.venue,jc.email_body,jc.interview_date,aj.job_id,aj.logo_image_url FROM jr_call_letter jc
JOIN api_job aj ON aj.job_id=jc.job_id ORDER BY "jc.job_id" DESC LIMIT 2 """
cursor.execute(sqlQuery)
result=dictfetchall(cursor)
final_response_map = []
key=0
for result_new in result:
print key
response_map = {}
response_map['company_name']=result[key]['company_name']
response_map['job_id']=result[key]['job_id']
response_map['job_position']=result[key]['job_position']
response_map['interview_date']=datetime.fromtimestamp(result[key]['interview_date']).strftime('%d-%m-%Y')
response_map['email_body']=result[key]['email_body']
response_map['venue']=result[key]['venue']
response_map['logo_image_url']=result[key]['logo_image_url']
key=key+1
final_response_map.append(response_map)
response = {'data':final_response_map}
data = json.dumps(response, encoding="ISO-8859-1")
return HttpResponse(data,content_type="application/json", status=200)
Please help me in getting a solution for this problem.
Your return statement is inside the if condition. If that condition is invalid it will go outside of the condition and expect a Response, but there is no return outside your condition, hence the error.
try providing this for checking:
def call_letter_track(request):
if request.META["CONTENT_TYPE"] == 'application/json':
'''
.
.
your code
.
.
'''
return HttpResponse(data,content_type="application/json", status=200)
return HttpResponse('Hello World')
The browser by default has the Content-Type header of application/xml and hence it is not entering your if condition.
Browser will not send CONTENT_TYPE header with application/json; causes the outer if block is never executed; The view function will not return.
How about Remove the outermost if so that request without Content-type: application/json also get HttpResponse?
def call_letter_track(request):
if request.META["CONTENT_TYPE"] == 'application/json': # <---
if request.method == 'GET':
....