I'm working on a project, using Flask. Apart from the index page, all other pages have '.html' extension displayed at the end of their URL (for example 127.0.0.1:5000/mypage.html), which is normal. For some reasons, i do not want the extension displayed, i prefer the URL displays with the extension (like this 127.0.0.1:5000/mypage. Here's what i have:
Flask
#app.route('/mypage', methods=['POST', 'GET'])
def mypage():
return render_template('/mypage.html')
HTML
Mypage</li>
I'll appreciate any help with this.
Following the documentation: Creating URLs in Flask, you can do this like this, and you are pretty much good to go.
Please Note: Do not use / inside the render_template
#app.route('/mypage', methods=['POST', 'GET'])
def index():
return render_template('mypage.html')
If you want to hardcode the url, you can use url_for(). But as the documentation says:
Flask can generate URLs using the url_for() function of the flask package. Hardcoding URLs in the templates and view functions is a bad practice.
HTML
Mypage</li>
Related
I googled the following question: How can I use the put method in HTML by form?
but I found many answers one of them is (Using PUT method in HTML form) for that, I need to use the put method because I would like to handle the response by Django in Views model so, in Views, there are many different methods to deal with requests like (GET, POST, PUT, and many others).
so, if I decided to use the put method, for example, I should as I understand get the request that has been modified by the PUT method as I believe that this is how Django works.
could anyone help, please?
thanks
I resolve my issue after I googled many times then I discovered that HTML only accepts two ways: POST and GET methods for handling the requests.
but I got a solution I don't know if it was a good solution or not by using hidden input I named it by "_put" then, I ran the put method into the post method like so:
class TestView(Views):
def post(self, request):
if "_put" in request.POST:
return self.put(request)
def put(self, request):
# TODO
As mentioned in the title, I attempt to
POST JSON file from C# (which is a WinForms accepting user input, then converted into a json), then to be received by python. I am quite clueless as to how to start at the C# side of the coding as I am still new to this. Would appreciate any kind help from here. Thanks
I use httpclient to communicate between the two languages, and now I would like to send the json file to the python side.
In short, the working principle of my project is:
User input parameters at WinForms that I have designed using C#, then these parameters are transferred over to Python by the flask and HTTPclient architecture.
Python process the parameters and a result is obtained, where I now wish to transfer this result back to C#, to be displayed on WinForms.
Flask is easy to use and set up for a simple POST request like this. The flask docs are excellent: https://flask.palletsprojects.com/en/2.0.x/quickstart/#a-minimal-application
Assuming you have pip installed Flask >= v2.0, a simple flask application to receive a POST request would look like:
from flask import Flask, request, jsonify
app = Flask(__name__)
#app.post('/submit_input')
def submit_input():
# check that your data is json
if request.json:
data = request.json
# do something with the data here and create a new var...
new_var = 'this is some new data'
return jsonify(message=new_var)
I'm currently sending data from my flask application to my HTML pages as dicts or list and I use templates rendering to display the values like {{data[0]}}, and I'm wondering is it a bad practice? should I use jsonify instead or it's the same thing?
I'm wondering is it a bad practice?
It's not a bad practice. It's what we called template rendering.
should I use jsonify instead or it's the same thing?
They are not the same thing. jsonify() will return a JSON reponse (Content-Type: application/json), while render_template() reutrn a HTML respone (Content-Type: text/html). The former pass pure data (for machine), the latter show a HTML page (for human).
Normally, you only use jsonify when building a REST API or making AJAX call.
I'm working on a second house pricing project, so I need to scrape information from one of the largest second house trading platform in China. Here's my problem, the info on the page and the corresponding element using Chrome 'inspect' function are as follows:
my code:
>>>from lxml import etree
>>>import requests
>>>url = 'http://bj.lianjia.com/chengjiao/101101498110.html'
>>>r = requests.get(url)
>>>xiaoqu_avg_price = tree.xpath('//[#id="resblockCardContainer"]/div/div/div[2]/div/div[1]/span/text()')
>>>xiaoqu_avg_price
[]
The returned empty list is not desirable (ideally it should be 73648). Furthermore, I viewed its HTML source code, which shows:
So how should I do to get what I want? And what is the resblockCard means? Thanks.
This site like many others uses ajax for populating content. If you make a similar request you can get desired value in json format.
import requests
url = 'http://bj.lianjia.com/chengjiao/resblock?hid=101101498110&rid=1111027378082'
# Get json response
response = requests.get(url).json()
print(response['data']['resblock']['unitPrice'])
# 73648
Note two group of numbers in request url. The first group from original page url, second you can find under script tag in the original page source: resblockId:'1111027378082'.
That XPath query is not working as expected because you are running it against the source code of the page as it is served by the server, not as it looks on a rendered browser page.
One solution for this is to use Selenium in conjunction with PhantomJS or some other browser driver, which will run the JavaScript on that page and render it for you.
from selenium import webdriver
from lxml import html
driver = webdriver.PhantomJS(executable_path="<path to>/phantomjs.exe")
driver.get('http://bj.lianjia.com/chengjiao/101101498110.html')
source = driver.page_source
driver.close() # or quit() if there are no more pages to scrape
tree = html.fromstring(source)
price = tree.xpath('//div[#id="resblockCardContainer"]/div/div/div[2]/div/div[1]/span/text()')[0].strip()
The above returns 73648 元/㎡.
I am currently trying to migrate a project from flask over to Django as practice and just to get it working on Django... I was wondering if there is a method within Django that performs the job of flask.jsonify?
If not, how else would you recommend I can emulate the same functionality?
from django.http import JsonResponse
def someView(request):
...
return JsonResponse(someDictionary)