i cannot access the text box data in the back end. i wanna use the textbox value in the backend but it says 400 badrequest. Please help me with this. i cannot see where my code went wrong.i cannot access the text box data in the back end. i wanna use the textbox value in the backend but it says 400 badrequest. Please help me with this. i cannot see where my code went wrong.
python
from flask import Flask, render_template, url_for, request,redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import tweepy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db= SQLAlchemy(app)
#app.route('/')
def index():
return render_template('home.html')
#app.route('/getlivedata', methods=['POST','GET'])
def stream():
if request.method =="POST":
rows = request.form['numtweets']
else:
return render_template('home.html')
if __name__ == "__main__":
app.run(debug=True)
html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - Navigation PageDesign/Lesson</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="sara mazal lessons">
<meta name="keywords" content="HTML, CSS, JavaScript, mazal, icons">
<meta name="author" content="Sara Mazal">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght#200;300;400;500&family=Raleway:wght#100;200;300;400;500&family=Roboto:wght#300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/particlesjs/2.2.3/particles.min.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}">
</head>
<body>
<!-- partial:index.partial.html -->
<section class="nav">
<h1>LIVE TWITTER DATA ANALYSIS</h1>
<h3 class="span loader">
<span class="m">S</spam><span class="m">E</spam><span class="m">N</spam><span class="m">T</spam><span class="m">I</spam><span class="m">M</spam><span class="m">E</spam><span class="m">N</spam><span class="m">T</spam><span class="m">A</spam><span class="m">L</spam><span class="m"> </span><span class="m">A</spam><span class="m">N</spam><span class="m">D</spam><span class="m"> </span><span class="m">C</spam><span class="m">A</spam><span class="m">T</spam><span class="m">E</spam><span class="m">G</spam><span class="m">O</spam><span class="m">R</spam><span class="m">I</spam><span class="m">C</spam><span class="m">A</spam><span class="m">L</spam> </h3>
<div class="nav-container"><a class="nav-tab" href="#tab-pwa">PWA</a><a class="nav-tab" href="#tab-graphql">GraphQL</a><a class="nav-tab" href="#tab-next">NEXT</a><a class="nav-tab" href="#tab-typescript">TYPESCRIPT</a><a class="nav-tab" href="#tab-deno">DENO</a><span class="nav-tab-slider"></span></div>
</section>
<form action="#" method="post">
<main class="main">
<section class="slider" id="tab-pwa">
<h1>PWA</h1>
<input type="text" name="numtweets">
<h3>GetLiveData</h3>
<h2>the best of both worlds...</h2>
</section>
<section class="slider" id="tab-graphql">
<h1>GraphQL</h1>
<h2>a query language for APIs</h2>
</section>
<section class="slider" id="tab-next">
<h1>NEXT</h1>
<h2>framework for Production</h2>
</section>
<section class="slider" id="tab-typescript">
<h1>TYPESCRIPT</h1>
<h2>giving you better tooling at any scale</h2>
</section>
<section class="slider" id="tab-deno">
<h1>DENO</h1>
<h2>a modern runtime</h2>
</section>
</main>
</form>
<canvas class="background"></canvas>
<!-- partial -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script><script src="{{ url_for('static',filename='js/script.js') }}"></script>
</body>
</html>
Change your form action to "/getlivedata" so it would post the data there. Also, it seems that you are using the as the way to go to the url. Use a submitnbutton instead.
Related
I have a basic web app - a blog - I am trying to create using Flask.
I am trying to use {{ url_for('static', filename='vendor/fontawesome-free/css/all.min.css') }} in my index.html to create a dynamic url. However, I am continually getting a GET request error because Jinja is not recognizing it as python code, and Flask is trying to create a url using the verbatim call.
Here is an example error:
"GET /%7B%20%7Burl_for(%22static%22,%20filename=%22vendor/bootstrap/css/bootstrap.min.css%22)%20%7D%7D HTTP/1.1" 404
The problem is not with the url_for() call or with the structure of my directory/inclusion of correct static and template folders because using
with app.test_request_context():
print(url_for('static', filename='vendor/fontawesome-free/css/all.min.css'))
in my main.py file prints the correct path.
Additionally, Jinja is properly installed and working as evidenced by the fact that {% include "header.html" %} and {% include "footer.html" %} both work because the attempts to create the urls are all in those files.
Here is my main.py
from flask import Flask,render_template, url_for
import jinja2
app = Flask(__name__)
#app.route('/')
def root():
return render_template('index.html')
with app.test_request_context():
print(url_for('static', filename='vendor/fontawesome-free/css/all.min.css'))
if __name__=='__main__':
app.run(debug=True)
Here is the relevant part of index.html
{% include "header.html"%}
<!-- Page Header -->
<header class="masthead" style="background-image: url('static/img/home-bg.jpg')">
...
</header>
<!-- Main Content -->
<div class="container">
...
</div>
{% include "footer.html"%}
Here is the footer.html :
<!-- Footer -->
<footer>
...
</footer>
<!-- Bootstrap core JavaScript -->
<script src="{{ url_for('static', filename='vendor/jquery/jquery.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
<!-- Custom scripts for this template -->
<script src="{{ url_for('static', filename='js/clean-blog.min.js') }}"></script>
</body>
</html>
Here is the header.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Clean Blog - Start Bootstrap Theme</title>
<!-- Bootstrap core CSS -->
<link href="{{ url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
<!-- Custom fonts for this template -->
<link href="{{ url_for('static', filename='vendor/fontawesome-free/css/all.min.css')}} " rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- Custom styles for this template -->
<link href="{{ url_for('static', filename='css/clean-blog.min.css')}} " rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
...
</nav>
One last note, before created the dynamic urls and doing a static reference, all the CSS/JS files rendered correctly.
Edit
The following code correctly renders the url on the page.
<h1>{{url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css', _external=True)}}</h1>
It's only when I wrap it as a string that it no longer picks it up as code.
In the content you've pasted in your question, there is a Unicode zero-width non-joiner character in between the two { markers in front of your Jinja expression. That is, if I copy this line from footer.html:
<script src="{{ url_for('static', filename='vendor/jquery/jquery.min.js') }}"></script>
And produce a hexdump from it, I see:
00000000: 2020 3c73 6372 6970 7420 7372 633d 227b <script src="{
00000010: e280 8c7b 2075 726c 5f66 6f72 2827 7374 ...{ url_for('st
00000020: 6174 6963 272c 2066 696c 656e 616d 653d atic', filename=
00000030: 2776 656e 646f 722f 6a71 7565 7279 2f6a 'vendor/jquery/j
00000040: 7175 6572 792e 6d69 6e2e 6a73 2729 207d query.min.js') }
00000050: 7d22 3e3c 2f73 6372 6970 743e 0a }"></script>.
Look at offset x10, where we see e2 80 8c; that's the UTF-8 encoding of U+200c:
>>> "\u200c".encode()
b'\xe2\x80\x8c'
If I remove those extraneous characters from your source, everything works correctly:
$ curl -s localhost:5000 | grep static
<link href="/static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/vendor/fontawesome-free/css/all.min.css " rel="stylesheet" type="text/css">
<link href="/static/css/clean-blog.min.css " rel="stylesheet">
<header class="masthead" style="background-image: url('static/img/home-bg.jpg')">
This is a test /static/foo/bar
<script src="/static/vendor/jquery/jquery.min.js"></script>
<script src="/static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/static/js/clean-blog.min.js"></script>
I have the following files on VS code and when I try to run them on my browser, it fails to identify that there is any reg.html template at all. What is the issue?
python file
from flask import Flask,
render_template, flash
app = Flask(__name__)
app.config["SECRET_KEY"] = "asdfghjkl"
#app.route("/")
def form():
return render_template("reg.html", title = "Form")
if __name__ == "__main__":
app.run(debug = True)
html file (reg.html)
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login/Signup - ((title)) </title>
<!-- Bootstrap CSS-->
<link rel = "stylesheet" href = "(( url for('static', filename = 'css/bootstrap.min.css)' ))">
<link rel = "stylesheet" href = "(( url for('static', filename = 'css/site.css') ))">
</head>
<body>
<div class = "container">
<div class = "row">
<div class = "col-md-5">
<h1 class = "text-center">Registration form</h1>
</div>
<div class = "col-md-2"></div>
<div class = "col-md-2"></div>
</div>
</div>
<!-- Javascript -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.js.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src = "((url for ('static', filename = 'js/bootstrap.min.js')))">`</script>`
</body>
</html>
To solve this question, create a folder named templates, which is where Flask looks for templates by default, then put the reg.html in this folder:
start the program and you will observe the results:
Detailed information about flask, you can refer to Flask Tutorial.
from flask import Flask, render_template, url_for, jsonify, request
from translate import Translator
en_ge = Translator("geo")
ge_en = Translator("en","geo")
app = Flask("Translator")
#app.route("/send",methods=["GET","POST"])
def send():
if request.method == "POST":
word = request.form["word"]
return render_template("translator.html",word=en_ge.translate(f"{word}"))
return render_template("index.html")
app.run()
I am trying to make translator with flask, but unfortunately I start learning it 10 minutes ago :). I am just trying to win a bet and make it as fast as I can. Googled but I keep receiving server internal error. How to fix it, please help
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Translator</title>
</head>
<body>
<h1>შეიყვანე სიტყვა</h1>
<form method="POST" action="/send">
<div class="form-group">
<input type="text" name="word">
</div>
<input class="btn btn-primary" type="submit" value="Translate">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h1>{{word}}</h1>
</body>
</html>
I think u miss template_folder param in Flask object creation, something like
app = Flask("Translator", template_folder="full_path_fo_a_folder_where_your_html_is_stored")
I am trying to display my html files using python alone. Such as I would python code.py and I would be able to access my html at localhost:8080
html files are static files that access each other. For example, index.html directs to contact.html and all of them access css folder.
How do I open my html files so it displays it on the webpage?
below is what I have so far.
html_file = []
with open("index.html", "r") as f:
for line in f.readlines():
html_file.append(line)
Is there way to do python code.py and when I access localhost:8000 that would show me the code? and I can access each page.
here is an example html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<img class="resize" src="./pictures/logo.png" alt="logo">
<nav>
<ul class="nav-links">
<li class="active">Home</li>
<li>Contact</li>
</ul>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')
})
</script>
</nav>
</header>
</body>
</html>
There's way to do so using the python web frameworks like Flask or Django. In a typical flask scenario your code would look like this:-
1) Install flask:-
pip install flask
2) Write your code.py like this:-
from flask import Flask, url_for
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('hello.html')
3) Next create a templates folder inside which put your html file which I have named it to be hello.html
templates > hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<img class="resize" src="./pictures/logo.png" alt="logo">
<nav>
<ul class="nav-links">
<li class="active">Home</li>
<li>Contact</li>
</ul>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')
})
</script>
</nav>
</header>
</body>
</html>
4) Your directory structure would look like this:-
/code.py
/templates
/hello.html
5) Run python code.py and you can see your page on localhost:5000.
I began switching from using standard basic SQL in my flask app to using peewee and am getting a weird bug I cant seem to find any info about. My endpoints are working fine but when I tried going to the landing page I get "jinja2.exceptions.UndefinedError: 'peewee.IntegerField object' has no attribute 'flags'"
This seems like some weird interaction with wtforms and peewee but I cant seem to find similar issues. Thanks in advance.
Note everything is in one file
My Models:
class pipelineForm(FlaskForm):
pipeline = IntegerField('Pipeline ID')
class Process(Model):
pipeline_id = IntegerField()
process_name= CharField(null = True)
log= CharField(null = True)
exit_code= IntegerField()
started= CharField(null = True)
finsihed= CharField(null = True)
class Meta:
database=db
End Point for Landing Page:
#app.route('/bloodhound', methods=['GET','POST'])
def index():
form =pipelineForm()
print(form.errors)
if form.validate_on_submit():
print(str(form.pipeline.data))
return redirect(url_for('.display', pipelineId=form.pipeline.data))#'<h1>' + str(form.pipeline.data) + '</h1>'
return render_template('index.html',form=form)
Landing Page:
{% extends "bootstrap/base.html" %} {%import "bootstrap/wtf.html" as wtf%} {% block content %}
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Narrow Jumbotron Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="../../dist/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="../../assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="jumbotron-narrow.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="../../assets/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/bloodhound">Bloodhound</a>
</div>
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>Performance</li>
</ul>
</div>
</nav>
<body>
<div class="container">
<div class="jumbotron">
<h1>Welcome to Bloodhound!</h1>
<p class="lead">Enter a pipeline Id to get diagnostic information.</p>
<form class="input" method="POST" action="/bloodhound">
<div class="input-group" style="width: 300px;">
{{form.hidden_tag()}} {{wtf.form_field(form.pipeline)}}
<span class="input-group-btn" style="vertical-align: bottom;">
<button class="btn btn-default" type="submit" >Go!</button>
</span>
</div>
</form>
</div>
<footer class="footer">
<p>© 2017 MITRE.</p>
</footer>
</div>
<!-- /container -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
{% endblock %}
Full Stack Trace
Traceback (most recent call last):
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/patrick/process_tracker/api/tracker_api.py", line 201, in index
return render_template('index.html',form=form)
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/templating.py", line 134, in render_template
context, ctx.app)
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask/templating.py", line 116, in _render
rv = template.render(context)
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/jinja2/environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/jinja2/environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/jinja2/_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "/home/patrick/process_tracker/api/templates/index.html", line 1, in top-level template code
{% extends "bootstrap/base.html" %} {%import "bootstrap/wtf.html" as wtf%} {% block content %}
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 1, in top-level template
code
{% block doc -%}
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 4, in block "doc"
{%- block html %}
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 20, in block "html"
{% block body -%}
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 23, in block "body"
{% block content -%}
File "/home/patrick/process_tracker/api/templates/index.html", line 58, in block "content"
<!-- {{form.hidden_tag()}} {{wtf.form_field(form.pipeline)}} -->
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/jinja2/runtime.py", line 553, in _invoke
rv = self._func(*arguments)
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/flask_bootstrap/templates/bootstrap/wtf.html", line 36, in template
{% if field.flags.required and not required in kwargs %}
File "/home/patrick/enviroments/venv/lib/python3.5/site-packages/jinja2/environment.py", line 430, in getattr
return getattr(obj, attribute)
According to your error message this field
class pipelineForm(FlaskForm):
pipeline = IntegerField('Pipeline ID')
is of type pewee.IntegerField and you wan it to be the IntegerField type of WTForms. If you have both classes in the same file you need to:
import pewee
import wtforms.fields
class pipelineForm(FlaskForm):
pipeline = fields.IntegerField('Pipeline ID')
class Process(Model):
pipeline_id = pewee.IntegerField() # and so on