I have two questions. I am new to python and not fluent enough with all the BIF's in python.
I am developing a website database is on amazon simple db.
I am handling all database related queries and code using python scripts.
My first question is given an HTML page where the user gives his his login credentials I call in a python script using my handler javascript function send in a post request and get a response from my python script.
I can send a post request all right and get the values from sdb for validation. What I need to know is how to send in a response from my script back to my html page which could react to the information given.
My second question is how do I maintain an HTTP session using python?
My python code is given below although it shouldn't make for much since no response code is added:
form=cgi.FieldStorage()
organisationID= form['orgID'].value
username= form['username'].value
password= form['password'].value
sdb=sdbhelper.connect()
connection= sdb.get_domain('AdminTable')
itemnames=''
flag=False
for item in connection:
if (item.name==username+'$'+organisationID):
retrieved_item=connection.get_item(item.name)
if(retrieved_item['Password']==password):
flag=True
#Now Id like to respond with flag so that login validation can be done
If I am correctly getting your question what you want to do is to create a small API , Where you send some information to a webpage and get some other .
What you can do is once the user is authenticated you should return it a access key that is valid for a short time period .
One of the way to send data could be inform of JSON objects .
For example if user is authenticated then return
{
'KEY' : 'dklsfeir5rufui435uejhfjh5ewh5rf'
}
From the next request you can associate this short lived key along the url for access .For example send the next request to abc.py?key=dklsfeir5rufui435uejhfjh5ewh5rf (by get or by post ) . If the key is valid then process the request else send a json response saying error occurred .
The main advantage of using JSON is it can be easily decoded/ encoded for communication
(JSON | http://docs.python.org/2/library/json.html )
Secondly as you have generated access key you would not require any session .
Related
I am trying to create a bot that joins the server by putting in a name and pressing a button that connects the request into the server., but in requests. The system hasn't been working as supposed to. It is supposed to POST the information in the correct places with the json.
payload = {
'idOftheInputBar': 'Username'
}
After that, I tried posting, getting, and patching but the response ended up with 404 or 200 but didn't send. How can make a request join the public server after putting in a username?
I am trying to update an already saved form on a system using HTTP requests. Due to the server configuration for the third party app we use, updating by POST requires sending a fully filled out payload every single time.
I want to get round this by recovering the form data already present on the server and converting it into a dictionary. Then changing any values I need and reposting to make changes sever side.
The application we use sends a POST request when the save button is clicked for a particular form.
Here I send a post request with no payload.
[This simulates pressing the save button and is also the point where dev tools shows me a the payload I want to capture]
post_test = self.session.post(url_to_retrieve_from)
I thought that now I should be able to print the output, which should resemble what Google Dev tools Form data captures.
print(post_test.text)
This just gives me html found on the webpage.
If Dev Tools can get this from the server then I should also be able to?
Example of Data I am trying to get via requests:
Form Data
If Dev Tools can get this from the server then I should also be able to?
Yes, of course. In requests you pass form data in data keyword:
import requests
url = 'http://www.example.com'
data = {
'name': 'value',
}
response = requests.post(url, data=data)
You can get the data you sent with a request from the response in this way:
import requests
response = requests.post('http://your_url', data=data) # send request
body = response.request.body
parsed_data = dict(data.split('=') for data in body.split('&')) # parse request body
Here you can find more information about data argument
In the documentation, in the class requests.Response we can find the attribute:
request = None
The PreparedRequest object to which this is a response.
In requests.PreparedRequest class we can read:
body = None
request body to send to the server.
I'm looking for a value. It is a session ID.
I analyzed network activity and the only reference to such a thing is "Access-Control-Allow-Headers: x-site-sessionid"on a request response header.
I also found it at the end of the POST request (sessionid=xxxx) but I need that value beforehand so my script can work. On my browser it does it automatically but I've been unable to find the value's source or how to request it from the site.
How would I pull this value? Everything else with the script is working as I tested it with an old session ID (that I got from a post request in my network activity log) and it registered fine. Though this isn't ideal for multiple runs.
Parameters that appear in the url address are not POST parameters , you simply need to add the session_id that your receive in the OPTIONS request to the url of the POST , like so:
session_id = 'get options response'
request.post(url + "&sessionid=%s" % session_id, data = {})
This is my first application using Flask and Python.
I am using below URL format to send a POST request from Arduino to the flask application running on Pythonanywhere server instance.
Valid POST request: 3 URL parameters
http://voyagers.pythonanywhere.com/senddata?node=1234&lat=18.5580&lng=73.8075
I need to block the request from further processing by validating the URL in some form. I want this to secure my app from un-authenticated POST requests.
Say something like this:Anything more than 3 URL Parameters
http://voyagers.pythonanywhere.com/senddata?node=324&lat=18.5580&lng=73.8075&a=c&a=d
How can I achieve this in Flask ?
Also suggest , If there is any better way which could be used to secure application from un-authorised requests.
You can get flask to validate the parameters and throw an error automatically if you are willing to switch from URL parameters (i.e. anything after the '?' symbol in the URL) to path parameters (i.e. anything that is in the Path HTTP header, or the part of the URL after the first '/' and abefore the '?').
Your example could look like this:
#app.route('/post/<int:node_id>/<float:lat>/<float:lng>', methods=['POST'])
def process_post_request(node_id, lat, lng):
# do some work
return your_result
Then you could send request to URL that would look for example like this: http://example.com/post/1234/-11.45/21.34
You can find more about this here: http://flask.pocoo.org/docs/0.12/quickstart/#variable-rules
For securing access you can use some of the example snippets here: http://flask.pocoo.org/snippets/category/authentication/
I would recommend restricting access to HTTPS only and using the basic auth if you are just playing around. This is something you can do with a simple decorator as described here: http://flask.pocoo.org/snippets/8/
You will get a prompt in your browser asking you for username and password and browser will remember it for the duration of the session. Alternatively, you can set the username and password in base64 encoded form in the Authorization header: https://en.wikipedia.org/wiki/Basic_access_authentication
I am trying to understand how to use AJAX with Python Sessions. I understand the basics of how sessions work. When I add AJAX to the mix, my mind is having a difficult time understanding the technical details. Part of me thinks AJAX and Python Sessoins are not possible. I know web frameworks exist that probably do all this magic but I want to learn how to do it myself before jumping into a framework.
I am trying to create a webpage with a login form using HTML, AJAX, Python, and Sessions. If the user is able to log in, a session should be created (I assume that's correct). Otherwise, an error message should be returned.
Here is the basic application layout:
login.html : HTML form with username & password input boxes and
submit button
ajax.js : contains AJAX function that communicates with server-side
script
check_user.py : checks if username & password are correct, creates
session or returns error
welcome.html : only accessible if username & password are correct
welcome_1.html : only accessible if username & password are correct
I prefer to keep the HTML, Javascript, and Python code in separate files as opposed to creating HTML with Python or using inline Javascript in HTML.
Here is the application logic:
user visits login.html
enters username & password
clicks submit button
submit button calls ajax function
ajax function sends username & password to check_user.py
check_user.py checks if username & password are correct
if not correct, return JSON formatted error message
else, correct
create session ID (SID)
place SID in cookie
return cookie to ajax function
redirect user to welcome.html
welcome.html
on page load, ajax function requests user's cookie
if no cookie, redirect to login.html
else, ajax function sends cookie to check_user.py
check_user.py opens cookie & verifies the SID
if not correct, redirect user to login.html
else, correct
redirect user to welcome.html
I think I am misunderstanding how ajax is supposed to handle the returned cookie information. It is also possible that I am misunderstanding other parts, too. Please clarify :-)
I think I will follow this document when writing my Python session code. Sound ok?
I am considering using jQuery for the AJAX stuff and other Javascript coding.
Thank you!
Remember that the AJAX request is the same as any other HTTP request to the server. The session is maintained on the server side, but as far as the server can tell, a request from the browser is a request from the browser. An AJAX request can get and set the cookie just like any other request can. The method you've outlined above should work fine. Alternately, you could check for the existence of the session on your front page, and write the cookie then.