This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 6 months ago.
I am using Flask in python with HTML.
I do not receive anything from the form, I do not know what I have wrong, I leave my code below.
I get "none" from the form when I execute the request.form.get("url")
HTML
<!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>YouTube Download</title>
<link rel="stylesheet" href="../static/css/style.css">
<link href="{{ url_for('static', filename='css/style.css') }}" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="banner">
<h1 class="title" data-text="Youtube Download"><i class="fa fa-music"></i> Youtube Download</h1>
<form action="{{ url_for('downloadMP3') }}" method="POST">
<p>Ingresa la URL del Video
</p>
<br>
<input class="form-control" type="text" id="url" name=“url” >
<div class="btn-group">
<button class="btn" type="submit" formaction="/downloadMP4">
<i class="fa fa-download"> </i> Download MP4
</button>
<button class="btn" type="submit" formaction="/downloadMP3">
<i class="fa fa-download"> </i> Download MP3
</button>
</div>
</form>
</div>
</body>
</html>
PYTHON FILE
from flask import Flask, render_template, request, Response, redirect, send_file
import os
from os import remove
import pafy
import moviepy.editor as mp
app = Flask(__name__)
path=os.getcwd() + '/'
#app.route('/')
def route():
return render_template('index.html')
#app.route('/downloadMP4', methods=['GET', 'POST'])
def downloadMP4():
if request.method == 'POST':
url = request.form.get("url")
video = pafy.new(url)
best = video.getbest(preftype="mp4")
best.download(path)
p = path + video.title + '.mp4'
return send_file(p, as_attachment=True)
#app.route('/downloadMP3', methods=['GET', 'POST'])
def downloadMP3():
if request.method == 'POST':
url = request.form.get("url")
video = pafy.new(url)
best = video.getbest(preftype="mp4")
best.download(path)
name = path + video.title + '.mp4'
clip = mp.VideoClip(name)
clip.audio.write_audiofile(path + video.title + '.mp3')
p = path + video.title + '.mp3'
return send_file(p, as_attachment=True)
if __name__ == '__main__':
app.run(host='localhost', port=5000)
I think the problem is in the HTML form but I don't know.
Any help is helpful, thanks.
To your input-field you have to add a name attribute
<input class="form-control" type="text" id="url" name="url">
should do the job. When sent to the flask-backend request.form.get() does not look for the id but the name attribute.
You got None because you didn't specify the name attribute in your url field, like this:
<input class="form-control" type="text" id="url" name="url">
request.form.get() looks at the value of name attribute and not the id
When I try to add a new task on my website I get the message "POST /templates/todo" Error (404): "Not found" and cannot find what is wrong with the code. Can anyone help me figure it out? It was done on cs50ide software. If anyone could inform me whether I am able to create a functioning link for my website (I use python, flask, html and css) I would be very grateful! Thank you so much
add.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/css/styles.css" rel="stylesheet">
<title>
Add a New Task :)
</title>
</head>
<body>
<h1 class = "aligncenter">
<img class = "img1" src = "/static/images/logocarol.jpg" alt = "Logo" height = "200" width = "550"/>
</h1>
<h1 class="centergeneral fontsize">
Add any goals, dreams and aspirations you might have here:
</h1>
<form class="aligncenter" action="todo" method="POST">
<input id="task" name="task" type="text" placeholder="New Task :)">
<input id="submit" type="submit" disabled>
</form>
<script>
document.querySelector('#task').onkeyup = function(){
if (document.querySelector('#task').value === ''){
document.querySelector('#submit').disabled = true;
} else {
document.querySelector('#submit').disabled = false;
}
}
</script>
<form action="/">
<button type="submit" id = "back" class="btn btn-info margin"> BACK TO HOMEPAGE </button> <br> <br>
</form>
<form action="todo">
<button type="submit" id = "back" class="btn btn-outline-info margin"> BACK TO TO DO LIST </button> <br> <br>
</form>
</body>
todo.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/css/styles.css" rel="stylesheet">
<title>
To Do List! :)
</title>
</head>
<body>
<h1 class = "aligncenter">
<img class = "img1" src = "/static/images/logocarol.jpg" alt = "Logo" height = "200" width = "550"/>
</h1>
<h1 class="fonts centergeneral"> To Do List </h1>
<h2 class="fs-4 centergeneral"> What I Want to Achieve: </h2> <br>
<ul class="listcenter">
<script>
{%for todo in todos%}
<li> {{ todo }} <input type="checkbox" id="checkbox1"> </li>
{%endfor%}
</script>
</ul>
<a class="btn btn-outline-info margin" href = "add"> Add a New Task</a>
<a class="btn btn-outline-info" href = "clear"> Clear Tasks </a> <br>
<div class="backbuttons">
<form action="/">
<button type="submit" id = "back" class="btn btn-info"> BACK TO HOMEPAGE </button> <br> <br>
</form>
</div>
application.py code:
from flask import Flask, render_template, send_from_directory, request, redirect, session
from flask_session import Session
from cs50 import SQL
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/f1inschools')
def f1():
return render_template('f1inschools.html')
#app.route('/pdwt')
def pdwt():
return render_template('pdwt.html')
#app.route('/pros')
def pros():
return render_template('pros.html')
#app.route('/bookrecommendations')
def books():
return render_template('bookrecs.html')
#app.route('/todolist')
def todo():
if "todos" not in session:
session["todos"] = []
return render_template('todo.html', todos=session["todos"])
#app.route('/clear')
def clear():
return redirect("/todolist")
session["todos"] = []
#app.route('/add', methods=["GET", "POST"])
def add():
if request.method == "GET":
return render_template("add.html")
else:
todo = request.form.get("task")
session["todos"].append(todo)
return redirect("/todolist")
The function for adding tasks is at app.route("/add",methods=["GET","POST"]), but your form in the HTML has action="todo", so your form tries to send data to /todo which is nonexistent. To fix, simply change action="todo" to action="add".
How can you use flask to make the text of your website blue? I only know how to display text on your website. My code :
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return '''Hello world'''
Despite the negative feedback from other user, this is not that bad of a question, besides apart of #go2nirvana no one answered your question.
Note
Despite this is more a Front-end question related to CSS or Javascript and not HTML (yes you can embed CSS inline within HTML but is not recommended) what you asked can be achieved in Flask in many ways.
Example 1 -Hard coding, not recommended buy you can do it-
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
my_html = '''
<body style="background-color: #e1eb34;">
<h1 style="color: #002aff;">Hello World</h1>
</body>
'''
return my_html
if __name__ == '__main__':
app.run(debug=True)
or
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return '''
<body style="background-color: #e1eb34;">
<h1 style="color: #002aff;">Hello World</h1>
</body>
'''
if __name__ == '__main__':
Example 2 -Using Jinja2 DOCS##
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
color = {
'blue': '002aff',
'yellow': 'e1eb34',
'green': '28fc03',
'red': 'fc1703',
'purple': 'b503fc'}
return render_template('index.html', color=color)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="background-color: #{{color['yellow']}};">
{% for hue in color.values() if hue != 'e1eb34'%}
<h1 style="color: #{{hue}};">Hello World</h1>
{% endfor %}
<h1></h1>
</body>
</html>
Example 3 -Adding request, session, redirect, url_for and more fun
from flask import Flask, render_template, redirect, url_for, request, session
import random
app = Flask(__name__)
app.config['SECRET_KEY'] = 'dev'
color = {
'blue': '002aff',
'yellow': 'e1eb34',
'green': '28fc03',
'red': 'fc1703',
'purple': 'b503fc',
'orange': 'FF9733 ',
'black' : 'FFFFFF',
'light-blue': '0AE5E3',
'pink': 'FF95AE',
'blue-green' : '95FFCA'}
#app.route('/', methods=['GET', 'POST'])
def index():
error = None
if 'color' not in session:
session['color'] = None
session['background'] = None
if request.method == 'POST':
choice = request.form['color'].lower()
if choice not in color:
error = 'Color not in list'
return render_template('index.html', color=session['color'], background=session['background'], error=error )
else:
session['color'] = color.get(choice)
session['background'] = random.choice(list(color.values()))
return redirect(url_for('index'))
return render_template('index.html', color=session['color'], background=session['background'], error=error )
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
{% if color%}
<style>
body {
color: #{{color}};
background-color: #{{background}};
}
</style>
{% endif %}
</head>
<body>
<h1>Hello World</h1>
{% if error%}
{{error}}
{% endif %}
<form action="{{url_for('index')}}" method="POST">
<label for="color">Choose a color</label>
<input type="text" name="color">
<input type="submit" value="PRESSS" name="i_talk-with_flask">
</form>
</body>
</html>
Variation with a Macro DOC
{% macro color_mix(color)%}
{% if color%}
<style>
body {color: #{{color}};}
body {background-color: #{{background_}};}
</style>
{% endif %}
{% endmacro%}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
{{color_mix(color)}}
</head>
<body>
<h1>Hello World</h1>
{% if error%}
{{error}}
{% endif %}
<form action="{{url_for('index')}}" method="POST">
<label for="color">Choose a color</label>
<input type="text" name="color">
<input type="submit" value="PRESSS" name="i_talk-with_flask">
</form>
</body>
</html>
Honestly this is only the tip of the iceberg of the option you can have. Now is this reccomended ? Probably not, because this it should be handle with CSS or then handle it with JavaScript.
However there may be planty of instances where you may want to use it from a Flask App, one of there are:
Testing Purposes.
Debugging.
Something related to a Database.
Fun
That's a CSS question, not Flask.
return '<span style="color: #00ccff;">Hello world</span>'
Answer to Question 2
I'm assuming that you mean taking an image from the web. Yes you can, but this is definitely a CSS/HTML related question. However following the same principle of my previous answer:
Picures taken from Unsplash
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
my_pic = 'https://images.unsplash.com/photo-1469980098053-382eb10ba017?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80'
return render_template('index.html', my_pic=my_pic)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="background-image: url(https://images.unsplash.com/photo-1600187734183-707cf1c0fd5a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1304&q=80);"
>
< <div>
<h1 style="color: white;">Picture from HTML</h1>
<img src="https://images.unsplash.com/photo-1600298881979-9b0c50d7abdf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=60" alt="opps">
</div>
<div style="color: white;">
<h1>Picture from Flask</h1>
<img src="{{my_pic}}" alt="oops">
</div>
</body>
</html>
I suggest you to learn it from HTML and CSS related topic rather than Flask (first learn some CSS and HTML basic):
CSS
HTML
That been said I have a more interesting a USEFUL answer that however requires basic knowledge of the use of a Database, I assume you are a beginner and you may have not yet this knowledge but soon or later you will. So even if you dont understand completely the following keep it in mind and come back later.
I prepared a mini app that using flask, flask_sqlalchemy (with sqlite3), html and Bootstrap.
This app does the following and will teach you these principle:
.1 Upload a picture into a Database.
.2 How to download a picture from the Database.
.3 Render the picture from the Database into the WebBroser.
FULL CODE FROM GITHUB
Some Code from this mini app
Initiate the database, configs and Picture table for the databse
In class FileContent(db.Model):
data = file.read() It saves in database the Binary version of thefile
-render_file = render_picture(data). It saves the decode version, so that you can you see it for render it in the webpages.
# Built-in Imports
import os
from datetime import datetime
from base64 import b64encode
import base64
from io import BytesIO #Converts data from Database into bytes
# Flask
from flask import Flask, render_template, request, flash, redirect, url_for, send_file # Converst bytes into a file for downloads
# FLask SQLAlchemy, Database
from flask_sqlalchemy import SQLAlchemy
basedir = 'sqlite:///' + os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data.sqlite')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = basedir
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'dev'
db = SQLAlchemy(app)
# Picture table. By default the table name is filecontent
class FileContent(db.Model):
"""
The first time the app runs you need to create the table. In Python
terminal import db, Then run db.create_all()
"""
""" ___tablename__ = 'yourchoice' """ # You can override the default table name
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False)
data = db.Column(db.LargeBinary, nullable=False) #Actual data, needed for Download
rendered_data = db.Column(db.Text, nullable=False)#Data to render the pic in browser
text = db.Column(db.Text)
location = db.Column(db.String(64))
pic_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def __repr__(self):
return f'Pic Name: {self.name} Data: {self.data} text: {self.text} created on: {self.pic_date} location: {self.location}'
Upload route, here is where the picture its sent to databse and processed with correct data
So here is what is going on in the app route:
def render_picture(data) --> Takes the bites raw version of the pic and return the decode version, so that it can be used to be display on the web.
data = file.read() : This is the raw data.This can be used for downloading the pic from database
render_file: decoded file so you can retrieve it and the render in the web page
#Render the pics, this Function converts the data from
request.files['inputFile'] so that in can be displayed
def render_picture(data):
render_pic = base64.b64encode(data).decode('ascii')
return render_pic
#app.route('/upload', methods=['POST'])
def upload():
file = request.files['inputFile']
data = file.read()
render_file = render_picture(data)
text = request.form['text']
location = request.form['location']
newFile = FileContent(name=file.filename, data=data,
rendered_data=render_file, text=text, location=location)
db.session.add(newFile)
db.session.commit()
flash(f'Pic {newFile.name} uploaded Text: {newFile.text} Location:
{newFile.location}')
return render_template('upload.html')
INDEX Route
# Index It routes to index.html where the upload forms is
#app.route('/index', methods=['GET', 'POST'])
#app.route('/')
def index():
return render_template('index.html')
INDEX HTML with the Form
<form method="POST" action="/upload" enctype="multipart/form-data">
<!-- File Upload-->
<div class="form-group">
<label for="inputFile">File input</label>
<input class="form-control-file" type="file" name="inputFile">
</div>
<!-- Location -->
<div class="form-group">
<label for="location">Location</label>
<input class="form-control" type="text" name="location">
</div>
<!-- Text -->
<div class="form-group">
<label for="text">Write Text</label>
<textarea class="form-control" name="text" id="text" rows="5" placeholder="Add a Description"></textarea>
</div>
<!-- Submit -->
<button type="submit" class="btn btn-primary">Submit</button>
</form>
I am trying to automate the Winross(market research tool) tables syntax to generate Open-end tables. I need to use two excel files for this for which I am planning to use Pandas. I am not sure how to load the excel files into pandas which are selected in HTML using input type = "file".
Adding both HTML and python codes below
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>OE Tables</title>
</head>
<body>
<form class="" action="getfile" method="post" enctype="multipart/form-data">
<h1>OE Tables Generator</h1>
<h3>Select OE data:</h3>
<input type="file" name="myfile" value=""><br><br>
<input type="submit" name="" value="Upload OE File"><br><br>
<h3>Select Code-frame:</h3>
<input type="file" name="myfile" value=""><br><br>
<input type="submit" name="" value="Upload Code-frame"><br <br>
</form>
</body>
</html>
from flask import Flask, render_template, request
import pandas as pd
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route('/getfile', methods=['GET', 'POST'])
def getfile():
if request.method == 'POST':
excel_file = request.files['myfile']
oedata = pd.read_excel(excel_file)
return oedata.head()
else:
result = request.args.get['myfile']
return result
Currently getting a page with below error:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
I'm using Python on Google App Engine as the backend for a Desktop/Mobile web app for video sharing. I'm having an issue uploading from an iPhone to the blobstore. Usually the page redirects after the upload URL is created, but this doesn't happen on the phone. Instead the browser navigates to the upload URL, but nothing is uploaded.
I can select a video to upload just fine, and if it's a long video, the phone will take awhile to navigate to the next page which seems to imply that something is being transferred, but nothing ends up in the blobstore.
Videos are uploaded with the following Python code.
class UploadPage(webapp2.RequestHandler):
def get(self):
upload_url = blobstore.create_upload_url('/uploadvideo')
template_values = {
'upload_url': upload_url,
}
template = JINJA_ENVIRONMENT.get_template('upload.html')
self.response.write(template.render(template_values))
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload = self.get_uploads()[0]
video = Videos(content=upload.key())
video.title = self.request.get('title')
video.description = self.request.get('description')
video.ratingDown = 0
video.ratingUp = 0
video.creator = users.get_current_user().nickname()
uniuqeIDFound = False
newID = random.randint(1000,9999)
while(uniuqeIDFound == False):
vids = db.GqlQuery("SELECT * "
"FROM Videos ")
uniuqeIDFound = True
for v in vids:
if (v.videoID == newID):
newID = random.randint(1,10000)
uniuqeIDFound = False
video.videoID = newID
db.put(video)
self.redirect('/home')
The upload page itself looks like this.
<!DOCTYPE html>
<html>
<head>
<title> Upload </title>
<meta charset="utf-8">
<link type="text/css" rel="stylesheet" href="/stylesheets/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
</head>
<body>
<div class="fill">
<div class="container">
<ul class="nav nav-tabs">
<li>Home</li>
<li class="active">Upload Video</li>
<li>Logout</li>
<li>Contact Us</li>
</ul>
<h2 class="addColor">Tribal Knowledge</h2><h3 class="addColor">Upload a Video</h3>
<form class="form-horizontal" action="{{ upload_url }}" method="POST" enctype="multipart/form-data">
<textarea placeholder="Title..." name="title" cols="50" rows="1" autofocus="autofocus" required></textarea><br>
<textarea placeholder="Description..." name="description" cols="50" rows="4" autofocus="autofocus"></textarea><br>
Upload File: <input type="file" name="file"><br> <input class="btn btn-success" type="submit" name="submit" value="Upload Video">
</form>
</div>
</div>
</body>
</html>