Suppose the following route which accesses an xml file to replace the text of a specific tag with a given xpath (?key=):
#app.route('/resource', methods = ['POST'])
def update_text():
# CODE
Then, I would use cURL like this:
curl -X POST http://ip:5000/resource?key=listOfUsers/user1 -d "John"
The xpath expreesion listOfUsers/user1 should access the tag <user1> to change its current text to "John".
I have no idea on how to achieve this because I'm just starting to learn Flask and REST and I can't find any good example for this specific case. Also, I'd like to use lxml to manipulate the xml file since I already know it.
Could somebody help and provide an example to guide me?
Before actually answering your question:
Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.
In your case, to make use of REST principles, you should probably have:
http://ip:5000/users
http://ip:5000/users/<user_id>
Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:
GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id>
So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.
Now, the answer to your question:
Below is a basic semi-pseudocode of how you can achieve what I mentioned above:
from flask import Flask
from flask import request
app = Flask(__name__)
#app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
if request.method == 'GET':
"""return the information for <user_id>"""
.
.
.
if request.method == 'POST':
"""modify/update the information for <user_id>"""
# you can use <user_id>, which is a str but could
# changed to be int or whatever you want, along
# with your lxml knowledge to make the required
# changes
data = request.form # a multidict containing POST data
.
.
.
if request.method == 'DELETE':
"""delete user with ID <user_id>"""
.
.
.
else:
# POST Error 405 Method Not Allowed
.
.
.
There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.
Let me know if I have gotten something wrong.
Here is the example in which you can easily find the way to use Post,GET method and use the same way to add other curd operations as well..
#libraries to include
import os
from flask import request, jsonify
from app import app, mongo
import logger
ROOT_PATH = os.environ.get('ROOT_PATH')<br>
#app.route('/get/questions/', methods=['GET', 'POST','DELETE', 'PATCH'])
def question():
# request.args is to get urls arguments
if request.method == 'GET':
start = request.args.get('start', default=0, type=int)
limit_url = request.args.get('limit', default=20, type=int)
questions = mongo.db.questions.find().limit(limit_url).skip(start);
data = [doc for doc in questions]
return jsonify(isError= False,
message= "Success",
statusCode= 200,
data= data), 200
# request.form to get form parameter
if request.method == 'POST':
average_time = request.form.get('average_time')
choices = request.form.get('choices')
created_by = request.form.get('created_by')
difficulty_level = request.form.get('difficulty_level')
question = request.form.get('question')
topics = request.form.get('topics')
##Do something like insert in DB or Render somewhere etc. it's up to you....... :)
Related
While using the Routes library I want to redirect certain URLs. The documentation says it can be achieved like this:
map.redirect("/legacyapp/archives/{url:.*}", "/archives/{url}")
And I am indeed able to redirect to a URL this way. However I am unable to map/parse the URL arguments from the request to the redirect. My code looks like this:
app.mapper.redirect( "/repository/status_for_installed_repository{url:.*}", "/api/repositories/check_updates/{url}" )
and if the app is passed this:
curl -L 'FQDN/repository/status_for_installed_repository?owner=qqqqqq&changeset_revision=e5f6ced3e91f&name=asdsadsadas'
it redirects me to
GET /api/repositories/check_updates
but I cannot find a way how to obtain the values of owner name and changeset_revision.
I expect this to be a common use case as generally you do not want to lose arguments when redirecting?
Any help is much appreciated. Thanks.
I ended up implementing it as follows:
def _map_redirects( app ):
"""
Add redirect to the Routes mapper and forward the received query string.
Subsequently when the redirect is triggered in Routes middleware the request
will not even reach the webapp.
"""
def forward_qs(environ, result):
qs_dict = urlparse.parse_qs(environ['QUERY_STRING'])
for qs in qs_dict:
result[ qs ] = qs_dict[ qs ]
return True
app.mapper.redirect( "/repository/status_for_installed_repository", "/api/repositories/check_updates/", _redirect_code="301 Moved Permanently", conditions=dict( function=forward_qs ) )
return app
I'm using Django and have a view to get/insert some records in database. Here's my code:
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
#api_view(('GET','POST'))
#renderer_classes((TemplateHTMLRenderer,))
#csrf_exempt
def cours_list(request):
if request.method == 'GET':
data = JSONParser().parse(request)
results = Lesson.objects.get(discipline=data.discipline)
return Response({'cours': results}, template_name='search_results.html')
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = LessonSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data, status=201)
return JSONResponse(serializer.errors, status=400)
So to get data I use GET and to insert a new record I use POST. First, is this the right way to do ? I read once that it't a bad idea to use GET whatever the situation.
Also, the GET code is not actually working (I'm getting a bad request error) and it seems that this is comming from JSONParser that is not able to parse the request.
Edit1
Here is the request that is sent:
GET http://127.0.0.1:8000/cours/?{%22discipline%22:%22Mathematiques%22,%22localisation%22:%22%22}
Edit2
I tried to print requet.GET, and this what it gives:
<QueryDict: {'{"discipline":"Mathematiques","localisation":""}': ['']}>
When trying to access request.data['discipline'], it says:
django.utils.datastructures.MultiValueDictKeyError: "'discipline'"
Should I use GET or POST to retrieve results Django
To retrieve use a GET
I read once that it't a bad idea to use GET whatever the situation
Not at all, as long as your GET operation contains no side effects (e.g. in your GET method you are only reading from the database.
The GET code is not actually working (I'm getting a bad request error)
data2 = JSONParser().parse(request) # you used data2
results = Lesson.objects.get(discipline=data.discipline) # and you used data
^
|____ data? data2?
You're not passing the GET parameters correctly
You need to pass GET params like this url/?param1=value1
To read that value you use param1 = request.GET['param1'] and param1 will be the string value1
What you are doing isn't passing a value:
GET http://127.0.0.1:8000/cours/?{%22discipline%22:%22Mathematiques%22,%22localisation%22:%22%22}
That's why you get an empty value ['']
<QueryDict: {'{"discipline":"Mathematiques","localisation":""}': ['']}>
You can pass the entire data as a JSON string if you want, but I prefer to break it down like this:
url/?discipline=Mathematiques&localisation=Quelquechose
with
discipline = request.GET['discipline']
localisation = request.GET['localisation']
That's absolutely normally to use GET method for information retrieving, see HTTP/1.1: Method Dediniton, 9.3:
The GET method means retrieve whatever information (in the form of an
entity) is identified by the Request-URI. If the Request-URI refers to
a data-producing process, it is the produced data which shall be
returned as the entity in the response and not the source text of the
process, unless that text happens to be the output of the process.
For POST method, it's a good practice to submit new data with POST request, see HTTP/1.1: Method Dediniton, 9.5:
The POST method is used to request that the origin server accept the
entity enclosed in the request as a new subordinate of the resource
identified by the Request-URI in the Request-Line. POST is designed to
allow a uniform method to cover the following functions:
................................................................
- Providing a block of data, such as the result of submitting a
form, to a data-handling process;
- Extending a database through an append operation.
Also, take a look at Which HTTP methods match up to which CRUD methods? it will give you more clear idea of how and when particular HTTP methods shall be used and help you in next further development.
I've just read this in the django doc :
Note that request.FILES will only contain data if the request method was POST
In the example given they do like that :
def upload_file(request):
if request.method == 'POST':
I've just read before that we can use some decorator of django like :
#require_http_methods(["GET", "POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
Even one called #require_post().
It's a question about syntax and I want to know :
if I use decorator, it will stop the function before its execution if i'm not requesting by POST ?
If 1) is True, isn't the decorators option much 'python cool' ?
Thanks in advance.
Besta
The decorators in django.views.decorators.http can be used to restrict access to views based on the request method. These decorators will return a django.http.HttpResponseNotAllowed if the conditions are not met.
View decorators
As for 2, if request.method == 'POST' is perfectly fine and used in function based views.
I am making a stock application, where, after a user types in a stock such as MSFT, they are redirected to .../stock?s=MSFT I have successfully made this part, but now I need Python to grab this current, unique URL so that I can parse the quote (in this case, the MSFT) out if it and save it as a new variable.
The easiest way I can think of is just to get the current URL, although I cannot seem to find a way to do this; using self.request... but this returned the error:
NameError: global name 'self' is not defined
The other ideas I came across was to use a form of urllib as it contains a specific .request_qs() method, although this requires me to pass the URL as a parameter, which should be unique every time because of the change in stock.
Here is the Python I currently have:
#app.route('/', methods=['GET', 'POST'])
def home_search():
if request.method == 'POST':
st = request.form['s']
return redirect(url_for('stock')+'?s='+st)
return render_template('stk.html')
#app.route('/stock', methods=['GET', 'POST'])
def stock():
#here I need to save the variable 'name' as the current URL. I can parse it later.
url="http://finance.yahoo.com/d/quotes.csv?s="+name"&f=snl1"
text=urllib2.urlopen(url).read()
return render_template('stock.html')
Many thanks in advance.
It's request (imported from the flask package), not self.request
The Flask docs have, as always, thorough documentation about variables in the URL: http://flask.pocoo.org/docs/quickstart/#variable-rules
#app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
On that occasion, you should read the whole Quickstart from the Flask docs: http://flask.pocoo.org/docs/quickstart/
You haven't posted any info on where the error occurs :) And I can't see where you're trying to access self.requests.
Looking at other Flask apps, it seems you should just access request instead.
Take a look at these examples: https://github.com/mitsuhiko/flask/tree/master/examples
My views.py code:
from django.template import Context, loader, RequestContext
from django.http import HttpResponse
from skey import find_root_tags, count, sorting_list
from search.models import Keywords
def front_page(request):
if request.method == 'get' :
str1 = request.getvalue['word']
fo = open("xml.txt","r")
for i in range(count.__len__()):
file = fo.readline()
file = file.rstrip('\n')
find_root_tags(file,str1,i)
list.append((file,count[i]))
sorting_list(list)
for name, count in list:
s = Keywords(file_name=name,frequency_count=count)
s.save()
fo.close()
return HttpResponseRedirect('/results/')
else :
str1 = ''
list = []
template = loader.get_template('search/front_page.html')
c = RequestContext(request)
response = template.render(c)
return HttpResponse(response)
def results(request):
list1 = Keywords.objects.all()
t = loader.get_template('search/results.html')
c = Context({'list1':list1,
})
return HttpResponse(t.render(c))
#this for everyone.
the flow is this:
1) I run my app on the server .
2)It shows me the search page due to the else part of the view "def front_page(request)", now I want to execute the if part of the view "def front_page(request)" because I want to execute my python code written there and the redirected to the view "def results(request)", how can I do that ?
3) what should I mention in "action" of the front_page.html and in urls.py so that I can get back to the same view again. because I could'nt get back to the same view that I want it is repetitively showing me the same search page.Please help.
To enlarge upon the answer posted by #Barnaby....by using action='#' your form will be posted to the same url as the url used in the get request for the form.
Then in your view code, you have logic that says - if the request for this url is a GET request then do the work to configure the form, otherwise, you assume it is a POST and then you can handle the response.
Additionally I would advise that the your view explicitly checks that the request is a POST and if not make the assumption that it is a GET, rather than the other way around (as you have it), this is safer, as GET and POST are not the only request types, and you definitely need to know that you are dealing with a POST request if you want to deal with variables submitted in the POST request.
Hope that helps
Short answer: action="#". This is a HTML trick to post back to the current URL.
The general answer to how to reference a view in a template is to use the url tag. You may also want to consider using Django's forms functionality.