I've been having this big issue with my python code. I'm trying to set a cookie, and sometimes the cookie gets set, but most of the time it just doesn't. I've been trying to print out the value of the cookie, and quite often (most of the time) it's None. Can anyone please help me find out what I've done wrong? I appreciate all help. Thanks in advance
This is my run.py file
from flask import Flask, request, url_for, redirect, render_template, make_response
import os
app = Flask(__name__)
app.secret_key = os.urandom(16)
#app.route('/')
#app.route('/home')
def home():
return render_template('home.html')
#app.route('/login', methods=['POST'])
def login():
user = request.form.get('username')
password = request.form.get('password')
response = make_response('')
response.set_cookie('id', 'test', domain='127.0.0.1')
return redirect('home')
if __name__ == '__main__':
app.run('127.0.0.1', debug=True)
And below here is my html code. (templates/home.html)
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Please login</h1>
<form method="POST" action="{{ url_for('login') }}">
<input type="text" name="username">
</br>
<input type="password" name="password">
</br>
<input type="submit">
</form>
</body>
</html>
what happens if you change your the part of your code to this
response = make_response(redirect('/home')
response.set_cookie('id', 'test')
return response
Related
This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
Python code
from flask import Flask, app, render_template, request
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 1
#app.route('/')
def index():
return render_template('index.html')
#app.route('/after', methods=['GET', 'POST'])
def after():
file = request.files['file1']
file.save('static/file.jpg')
return render_template('predict.html')
if __name__ == '__main__':
app.run(debug = True)
following is html code from 'index.html':
<html>
<form action="{{url_for('after')}}">
<input type= "submit" enctype = 'multipart/form-data' method ="POST">
<input type="file" name='file1'>
</form>
</html>
And follwing is the code from 'predict.html'
<html>
<body>
<img src="{{url_for('static', filename = 'file.jpg')" alt="">
</body>
</html>
I am trying to choose an image file by clicking on 'Choose file' button to submit it but while doing this I got the following error;
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'file1"
Set the enctype and method attributes for your form tag, not for input:
<html>
<form action="{{url_for('after')}}" enctype="multipart/form-data" method="POST">
<input type="submit">
<input type="file" name="file1">
</form>
</html>
I need to display the value that was entered in a form after the user clicks the submit button. It displays it for a split second but when the page reloads it's gone
<html>
<html>
<head>
<link rel="stylesheet" href="{{url_for('static',filename='main.css')}}">
</head>
<body>
<title> Patent Info </title>
<form action="" method="POST" >
Enter Room Number <input type="number" name="getInput" id="data" min="1" max="5">
<input type="submit" onclick="c.value = getInput.value">
<h4>Going to Room: <output name="c"></output></h4>
</form>
from flask import Flask, render_template, request
from random import randrange
app = Flask(__name__)
#app.route("/")
def main():
return render_template('index.html')
#app.route('/', methods=['POST'])
def my_form_post():
input_nopol = request.form['getInput']
if request.method == 'POST':
with open('nopol.txt', 'w') as f:
f.write(str(input_nopol))
return render_template('index.html', nopol=input_nopol)
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=80)
I know i can do it if i change from type submit to type button but then my POST method dose not work
Try This
<h4>Going to Room: <output name="c">{{ nopol }}</output></h4>
Just add this below <h4>Going to Room: <output name="c"></output></h4>
<p>{{ nopol }}</p>
I'm trying to execute a def/python script from flask, when clicked on button... but can't seem to figure it out.
Here's my Python Code
from flask import Flask, redirect, url_for, render_template, request
import webbrowser
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
def contact():
if "open" in request.form:
print("Test")
elif "close" in request.form:
print("Test 2")
return render_template('contact.html')
if __name__ == "__main__":
app.run(debug=True)
And here is my HTML Code
<html>
<head>
<title>Home page</title>
</head>
<body>
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h1>Test</h1>
<input type="submit" name="open" value="Open">
<input type="submit" name="close" value="Close">
{% endblock %}
</body>
</html> ```
I don't know what is in {% block content %} but you need to have a form in order to call backend where you provide the url route that you want to call and the method you want to use (usually with forms it's POST). Also in the /contact endpoint you need to provide #app.route('/contact') and that it would accept POST request #app.route('/contact', methods=['POST']). Modify your python and HTML to look like this:
from flask import Flask, redirect, url_for, render_template, request, jsonify
import webbrowser
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
#app.route('/contact', methods=['POST'])
def contact():
result = False
if "open" in request.form:
result = activate_lamp() # expecting True as a result of function
elif "close" in request.form:
result = deactivate_lamp()
return jsonify({'result': result}) # expecting True as a result of function
if __name__ == "__main__":
app.run(debug=True)
<html>
<head>
<title>Home page</title>
</head>
<body>
<h1>Test</h1>
<form action="{{ url_for('contact') }}" method="post">
<input type="submit" name="open" value="Open">
<input type="submit" name="close" value="Close">
</form>
</body>
</html>
The jsonify will return an object to the front end with default 200 response code. Then you can either do something with it or ignore it. The idea is that in the route you can call other functions, but you must return a valid HTTP response to the front-end, e.g. jsonify, or plain return '', 200 might be enough.
<!DOCTYPE html>
<html>
<head>
<title>Rango</title>
</head>
<h1>We Would Like to know your name </h1>
<h2>192.168.29.109</h2>
<label for="username">Username:</label>
<input type="text" id="username" name="username" maxlength="10"><br><br>
<button onclick="https://">GO FURTHER</button>
Submit<br />
About<br />
<img src="{{ user_image }}" alt="User Image">
</div>
</body>
</html>
from here python flask file I have only 1 file
#IMPORTING
from flask import Flask , render_template
from flask_script import Manager
from wtforms import StringField
import os
#Launching Server
app = Flask(__name__)
manager = Manager(app)
#Settings..!
PEOPLE_FOLDER = os.path.join('static', 'people_photo')
app.config['UPLOAD_FOLDER'] = PEOPLE_FOLDER
#Defining URL's And Rendering!
#app.route('/index')
def index():
full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'lkj.jpg')
return render_template("index.html", user_image = full_filename)
#app.route('/user/<name>')
def user(name):
return '<h1>Hey %s, Welcome to Flask</h1>' % name
#Deployment
if __name__ == '__main__':
manager.run()
#app.run(debug=True)
Okay so I wanted to pass the value from input field to python flask file where I have defined #app.route(/user/)
in the input field I asked someone's name he put the name and I wanted to take that name and put it in the user/ and display his name I can manually do that by writing the url myself like '192.168.29.10:5000/user/laxman' it would display 'Hey Laxman...etc' but I wanted that its done through the input field from that the parameters are passed and flask take that and display 'Hey Name...etc' so Can anyone help I only have two files and I have showed them already abobe SO anyone's help will be appreciated pls Thankyou
:)
If you want to ask anything ask I am gonna tell you! thankyou!
You can wrap your input into a form and submit it to the /user view.
<form action="/user">
<input type="text" id="username" name="username" maxlength="10"><br><br>
<button type="submit" name="button">Submit</button>
</form>
then in your view function
#app.route('/user')
def user():
who = request.args.get('username')
# Do something with who
return render_template("user.html", name=who)
I have started just learning Flask and tried to find an answer how to post to SQLite DB from webform. So far haven't managed to get it work and bit lost with this. I manage to print values from DB based on code sample from simplypython but don't know how to add new ones from webform.
I would need to be able to address elements, open connection to the database, Insert values, save and close the connection. As far as I am aware I should add the POST method to the app.py and use request.form statement to pull the elements when submit button is pressed.
then the code should automatically display all the values on index html, which already works. could you please help me with the code I need to add to app.py file to get values added to DB and what to add to form action webform-section on html file?
index.html
<!DOCTYPE html>
<html>
<head>
<title>Flask Intro</title>
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
</head>
<body>
<div class="container">
<h3 potsit </h3>
{% for post in posts %}
Titleotsikko: {{post.title }} <br>
Postotsikko: {{post.description}}
{% endfor %}
</div>
<div>
<form action="/????????????NOT SURE WHERE TO DIRECT" method="post">
<div>
<label for="title">title:</label>
<input type="text" id="title" />
</div>
<div>
<label for="description">description:</label>
<input type="text" id="description" />
</div>
<div class="button">
<button type="submit">Add to db</button>
</div>
</form>
</div>
</body>
</html>
app.py
from flask import Flask, render_template, request, session, g
import sqlite3
app = Flask(__name__)
#app.route('/')
def home():
g.db = sqlite3.connect("sample.db")
cur = g.db.execute('select * from posts')
posts = [dict(title=row[0], description=row[1]) for row in cur.fetchall()]
g.db.close()
return render_template("index.html", posts=posts)
if __name__=='__main__':
app.run(debug=True)
sql.py
import sqlite3
with sqlite3.connect("sample.db") as connection:
c = connection.cursor()
c.execute("DROP TABLE posts")
c.execute("CREATE TABLE posts(title TEXT, description TEXT)")
c.execute('INSERT INTO posts VALUES("Luck", "no luck.")')
EDIT
I made some changes based on the suggestion from Paul Rooney and created file called post.html, moved the form there from index.htmland added another #route on the app.py file. I believe I'm not far off but after trying to figure this out since Tuesday hoping to get it work. Unfortunately now I receive an error 405 'The method is not allowed for the requested URL.' and I'm stuck with this after trying different options.
post.html
<!DOCTYPE html>
<html>
<head>
<title>Flask post</title>
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
</head>
<body
<div>
<form action="/post" method="post">
<div>
<label for="title">title:</label>
<input type="text" id="title" />
</div>
<div>
<label for="description">description:</label>
<input type="text" id="description" />
</div>
<div class="button">
<button type="submit">Add to db</button>
</div>
</form>
</div>
</body>
</html>
(edited) app.py
from flask import Flask, render_template, request, session, g, redirect, url_for
import sqlite3
app = Flask(__name__)
#app.route('/')
def home():
g.db = sqlite3.connect("sample.db")
cur = g.db.execute('select * from posts')
posts = [dict(title=row[0], description=row[1]) for row in cur.fetchall()]
g.db.close()
return render_template("index.html", posts=posts)
#app.route('/post', methods=['POST'])
def post():
title=request.form['title']
description=request.form['description']
print title, description
return redirect(url_for('/'))
if __name__=='__main__':
app.run(debug=True)
To answer your original question you should pick an endpoint to post your data to and use that in both your flask app and the html form action.
I suggested post in comments but it could be anything. I think you've grasped what to do here but for completeness.
The HTML
<form action="/post" method="post">
The Python Code
Add a route to handle the POSTed data.
#app.route('/post', methods=['POST'])
def post():
# Do db stuff then redirect back to index page.
pass
Edited Question
You have an indentation error in your code, which is causing the 405 error. Your post function is inside your home function. Make it more like this
app.py
from flask import Flask, render_template, request, session, g, redirect, url_for
import sqlite3
app = Flask(__name__)
#app.route('/')
def home():
g.db = sqlite3.connect("sample.db")
cur = g.db.execute('select * from posts')
posts = [dict(title=row[0], description=row[1]) for row in cur.fetchall()]
g.db.close()
return render_template("index.html", posts=posts)
# One level of indentation removed from here downwards
#app.route('/post', methods=['POST'])
def post():
title=request.form['title']
description=request.form['description']
return redirect(url_for('home'))
if __name__=='__main__':
app.run(debug=True)
After that I see a 400 Bad Request error, which stems from the fact that you don't have name parameters in your html form.
The attempt to access the title and description values in the form dict in app.py will throw a KeyError exception, as those keys will not be present without the name parameter in the html.
If you add them e.g.
...
<input type="text" id="title" name='title'/>
...
<input type="text" id="description" name='description'/>
...
Then it will run all the way through your function.
The next issue will be
redirect(url_for('/'))
instead use
redirect(url_for('home'))
home being the name of the function called for path '/'.
After that you should be good to go.