I want to make a simple python script to be run in my server. What it's supposed to do is receive requests and return values according to requests it received.
I want to access the script with a way like http://example.com/thescript.py?first=3&second=4.
and make the script to read the first and second and to do jobs with the values.
How could I do this?
The easiest way is to use Flask:
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
first = request.args.get('first')
second = request.args.get('second')
return render_template('index.html', first=first, second=second)
if __name__ == '__main__':
app.run()
And the template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
First: {{ first }}
<br />
Second: {{ second }}
</body>
</html>
This code will simply print the two parameters provided.
Related
So trying to finish a lab using Flask Templates
Here is my python code:
cryptosnapshots = (requests.get(f"https://api.finage.co.uk/snapshot/crypto?quotes=false&trades=true&symbols=&apikey=XXX")).json()
snapshot = (cryptosnapshots['lastTrades'][:20])
#app.route('/crypto_data', methods = ['GET']) # define the first route, the home route
def show_crypto(): # define the function that responds to the above route
if request.method == 'GET':
return render_template('show.html', snapshot = snapshot)
if __name__ == '__main__':
app.run()
and here is my the code from the html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{% for snapshot in snapshots %}
<h2>Symbol: {{snapshot['s']}}</h2>
<p> Last Price: {{snapshot['p']}}<p>
{% endfor %}
</body>
</html>
When python returns the url and I add my "/crypto_data" endpoint, the page just shows up blank...is my error on the python side or the html side (or is it the api??)?
TIA!
Im expecting the url and endpoint to lead to an html list of all the last trading price from the first 20 cryptos on the list.
My first issue was breaking down the API json and I thought once that was solved it would be a breeze...
labs due Sunday, someone help lol
In the Jinja template, your are accessing a value name snapshots. But in your Flask code, you are defininig a value name snapshot.
Try replacing the value named snapshot by snapshots in your Flask app:
cryptosnapshots = (requests.get(f"https://api.finage.co.uk/snapshot/crypto?quotes=false&trades=true&symbols=&apikey=XXX")).json()
snapshot = (cryptosnapshots['lastTrades'][:20])
#app.route('/crypto_data', methods = ['GET']) # define the first route, the home route
def show_crypto(): # define the function that responds to the above route
if request.method == 'GET':
return render_template('show.html', snapshots = snapshot)
if __name__ == '__main__':
app.run()
I'm using os.listdir to get a list of subdirectories and want to display them as a table on a webpage. I'm using bottle for the web framework. I have seen in the bottle documentation that it can be done by creating an sqlite database from the list and loading it in from there but ideally I'm looking for a way to avoid that intermediate step. I haven't been able to find any documentation without the sqlite step and was wondering if it was possible?
Current code below displays the info I want on the webpage but as a single line of text.
Current Code:
Bottle App
from bottle import Bottle, template, route, run, static_file
import os
import sys
app = Bottle()
dirname = os.path.dirname(sys.argv[0])
#app.route('/static/<filename:re:.*\.css>')
def send_css(filename):
return static_file(filename, root=dirname+'/static/')
#app.route('/')
def index():
dir_loc = "/Users/me/Documents"
dir_data = list(os.listdir(dir_loc))
return template('index', data = dir_data)
run(app, host='localhost', port=8080, debug=True)
index.tpl
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="static/styling.css">
</head>
<body>
<div>
<p>Template for bottle showing {{data}}</p>
</div>
</body>
</html>
A SQL database is not needed (unless you want that for persistence). You can generate tables and lists with loops, nicely described in the Bottle doc PDF.
Here's a simple example:
server.py
from bottle import route, run, template
import os
#route("/")
def index():
dir_loc = "/Users/me/Documents" # replace "me" with your username
dir_data = list(os.listdir(dir_loc))
return template("index.tpl", data=dir_data)
if __name__ == "__main__":
run(host="localhost", port=8080, debug=True, reloader=True)
index.tpl
<!DOCTYPE html>
<html>
<body>
<table>
<tbody>
% for file in data:
<tr>
<td>{{file}}</td>
</tr>
% end
</tbody>
</table>
</body>
</html>
Ive made a flask script which runs fine however im trying to display some values in a table on another html page which for some reason is not happening.
i've already tried going through jinja2 documentation and a few other answers but it didn't help much.
the flask file.py
from flask import Flask,render_template,request
app = Flask(__name__)
from webscraper import keeda,display_tbl
#app.route('/', methods=['POST', 'GET'])
def scraper():
if request.method == 'POST':
url = request.form['url']
df=keeda(url)
return render_template(('completed.html',display_tbl(df)))
else:
return render_template('index.html')
if __name__ == '__main__':
app.run()
the completed.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Summary of Scraped Data</title>
</head>
<body>
<h1>This is what you got! </h1>
<div>
{{ display_tbl(df) }}
</div>
</body>
</html>
here's the error: jinja2.exceptions.UndefinedError: 'display_tbl' is undefined
i wanted to display a table with values on this page.
You are expecting more than what jinja2 can do for you. Please understand jinja2 is just a way to render templates which are eventually html and javascript, nothing fancy. So, in your case you cannot pass a Python function to your jinja2 template and expect that to run fine. What you can do here is to pass the data returned by display_tbl while rendering template like this:
def scraper():
...
return render_template(('completed.html', data=display_tbl(df))) # data= is important because this is how you are going to access your data in the template
…
def display_tbl(df):
… # Here you should be returning the data you want to display - a list or dict
In the template
<html>
<head>
<meta charset="UTF-8">
<title>Summary of Scraped Data</title>
</head>
<body>
<h1>This is what you got! </h1>
<div>
{{ render_data() }}
</div>
<script>
var d = data | tojson
function render_data() {
// implement the logic to handle how your data should be rendered
}
</script>
</body>
</html>
This is just a rough idea but as you can see you need to change the way you are perceiving jinja2 templates and their interaction with Python or Flask backend.
This question already has answers here:
Python Flask Render Text from Variable like render_template
(4 answers)
Closed 3 years ago.
I can not go to about_me page from the index page.
Error :
The requested URL was not found on the server.
and got url like "http://127.0.0.1:5000/%7B%7B%20url_for('about')%20%7D%7D".
from flask import Flask, redirect, url_for
app = Flask(__name__)
#app.route('/')
def index():
return '''
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
</head>
<body>
<p>welcome home</p>
about
</body>
</html>
'''
#app.route('/about')
def about_me():
return 'about me'
if __name__ == '__main__':
app.run(debug=True)
The formatting you're using to insert the url_for the about me page, namely:
about
Will only work inside of a Jinja template. Those templates get processed by the template engine before the response is returned, and during that processing the notation with the two braces {{ something }} gets recognized and interpreted differently.
Here however, you are not using this notation in a Jinja template, you are using it it in a normal string, a string that does not get processed and thus does not have anything replaced.
The correct way to achieve what you want, in this case would be to parameterize the string and pass the link through formatting. E.g:
#app.route('/')
def index():
return '''
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
</head>
<body>
<p>welcome home</p>
about
</body>
</html>
'''.format(about_me=url_for('about_me'))
Hope this helps!
I have user interface (angularJS) in which i need to upload a file without refreshing the page.Currently we are using Flask as web application framework.
I changed the index.html to below format so that without using form tags i am trying to read the uploaded file and store it.
Using ngclick method how to read the file from app.py ?
The following is the code snippet(index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Flask Bucket List App</title>
<link href="http://bootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
</head>
<body>
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload file</button>
</div>
</body>
</html>
code snippet of app.py
from flask import Flask, render_template, json, request
app = Flask(__name__)
#app.route('/')
def main():
return render_template('index.html')
#app.route('/upload/')
def upload_file():
print('uploaded file ',request.FILES['file1'].read())
return render_template('signup.html')
I tried various options but i could not find feasible option.
Thanks
vijay