Hi, I am having a problem to send data from python script to a web page via flask. After runnung code on my webpage it displays information: "none". The server is responding but I think there is a problem with sending data using get. I know that at this stage i can generate data in flask but my goal is to send arduino data from python script to flask and display it on website
script sending data:
import requests
import serial
import time
while True:
payload = {'c1_temp': '20', 'c1_press': '1013', 'c1_humid': '30', 'c1_gleba': '60'}
r = requests.get("http://127.0.0.1:5000/czujnik1", params=payload)
print(r)
time.sleep(5)
flask:
from flask import Flask, render_template, request
import requests
import time
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
return render_template("style.css")
#app.route('/czujnik1', methods=['GET', 'POST'])
def czujnik1():
data = []
c1_temp = request.args.get('c1_temp')
c1_press = request.args.get('c1_press')
c1_humid = request.args.get('c1_humid')
c1_gleba = request.args.get('c1_gleba')
data.append(c1_temp)
data.append(c1_press)
data.append(c1_humid)
data.append(c1_gleba)
return render_template("czujnik1.html", data = data)
return render_template("style.css")
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<title>Document</title>
</head>
<body>
<nav>
<div class="logo">KREATYWNA MŁODZIEŻ</div>
<div class="nav-opts">
BACK
Czujnik 1
Czujnik 2
Czujnik 3
</div>
</nav>
<div class="czujnik">
<h1>Czujnik 1</h1>
<div class="czujnik-wrapper">
<div class="czujnik-box">
<h2>Temperatura(℃)</h2>
<p>{{ data.0 }}</p>
</div>
<div class="czujnik-box">
<h2>Ciśnienie(hPa)</h2>
<p>{{ data.1 }}</p>
</div>
<div class="czujnik-box">
<h2>Wilgotność(%)</h2>
<p>{{ data.2 }}</p>
</div>
<div class="czujnik-box">
<h2>Wilgotność gleby(%)</h2>
<p>{{ data.3 }}</p>
</div>
</div>
</div>
</body>
</html>
When I do a command print(r.text)in the sending script i get something like this
html:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/css/style.css">
<title>Document</title>
</head>
<body>
<nav>
<div class="logo">KREATYWNA MŁODZIEŻ</div>
<div class="nav-opts">
BACK
Czujnik 1
Czujnik 2
Czujnik 3
</div>
</nav>
<div class="czujnik">
<h1>Czujnik 1</h1>
<div class="czujnik-wrapper">
<div class="czujnik-box">
<h2>Temperatura(℃)</h2>
<p>20</p>
</div>
<div class="czujnik-box">
<h2>Ciśnienie(hPa)</h2>
<p>1013</p>
</div>
<div class="czujnik-box">
<h2>Wilgotność(%)</h2>
<p>30</p>
</div>
<div class="czujnik-box">
<h2>Wilgotność gleby(%)</h2>
<p>60</p>
</div>
<div class="czujnik-box">
<h2>Do wypełnienia</h2>
<input type="text">
</div>
<div class="czujnik-box">
<h2>Do wypełnienia</h2>
<input type="text">
</div>
</div>
</div>
</body>
</html>```
It should be working but it isn't showing like that on the page.
Related
I am trying to pass in a list of classes into a checkbox (this works), and when the Submit button is clicked, I want to make a Post Request to send all the selected boxes to the backend and then also go to the next page (Does not work).
Here is my HTML page right:
<!doctype html>
<html lang="en">
<head>
<style>
h1 {color: rgb(240, 112, 38);}
</style>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
function myFunction() {
window.location.href="./classinfo";
}
function sendPOST() {
let formData = { user_classes: $("#user_classes").val() };
$.post("/class", formData)
};
</script>
</head>
<body style="background-color:powderblue;">
<div class="container">
<br>
<h1>What Classes Have You Taken</h1>
<div class="form-group row">
<label class="col-lg-12">
<form method="POST" action='/class'>
<label class="col-xs-6" style="font-family:verdana;">
{% for c in cs_req %}
<input type="checkbox" style="text-align:left;" name = 'user_classes' option value = "{{c}}" SELECTED> {{c}}<br></option>
{% endfor %}
</label>
<br>
<input class="btn btn-secondary" style="font-family:verdana;" type="Submit" onclick="sendPOST();MyFunction()">
</form>
</label>
</div>
<div id="content">
</div>
</div>
<script>
$(document).ready(function(){
$('.selectpicker').selectpicker();
})
</script>
</body>
</html>
and my backend function is this:
#app.route('/class', methods=["POST"])
def store_classes():
"'Based on checkboxes selected from checkboxes(), store the classes in txt'"
user_classes = request.form.getlist('class') #--> returns nothing
return render_template("class.html")
My onclick is not sending the post request or going to the next page. I'm not sure how to solve this so any advice is appreciated.
This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 11 months ago.
I created a Flask app to upload an image to predict its label. This is the code of the relevant part of app.py:
#app.route("/", methods=['GET', 'POST'])
def main():
return render_template("index.html")
#app.route("/submit", methods = ['GET', 'POST'])
def get_output():
if request.method == 'POST':
img = request.files['my_image']
licenseplate = "static/" + img.filename
img.save(licenseplate)
p = predictLicensePlate(licenseplate)
This is the index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Number Plate Recognition</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1 class="jumbotron bg-primary">Number Plate Recognition</h1>
<br><br>
<form class="form-horizontal" action="/submit" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Upload Your Image :</label>
<div class="col-sm-10">
<input type="file" class="form-control" placeholder="Hours Studied" name="my_image" id="pwd">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
{% if prediction %}
<img src="{{img_path}}" height="200px" width="300px">
<h2> Your Prediction : <i> {{prediction}} </i></h2>
{% endif %}
</div>
</body>
</html>
But when I upload an image I only get a placeholder image there as you see below. Can you figure out what is wrong with my code? The format of my image is png and the prediction works fine.
You need to set the img_path variable in your template:
<img src="{{img_path}}" height="200px" width="300px">
When running the webapp a 404 error appears, the error doesnt even allow my error html to run even when changing it to the most basic of templates. I dont know where my request is being not found.
Ive tried removing all of the style sheets from base.html to see if its those, I tried changing the error.html to see if it will actually run I've attempted to comment out all url_for's in the html files.
I commented out the results bit so i dont think its that.
routes.py
from app import app
from flask import Flask, abort, jsonify, redirect, url_for, request, render_template
from werkzeug.exceptions import HTTPException
from app.results import clean_data, get_response
#app.errorhandler(Exception)
def handle_error(e):
'''
code = 500
if isinstance(e, HTTPException):
code = e.code'''
print(str(e))
return render_template("error.html")
#app.route('/', methods=['GET', 'POST'])
def index():
data = clean_data(request.form)
response = get_response(data)
print(response)
return render_template("index.html")
base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Default Scorer -- Ebury</title>
<meta name = "viewport" content = "width=device-width", initial-scale = 1, shrink-to-fit=no">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}">
<!-- CSS-->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<link href="https://fonts.googleapis.com/css?family=Roboto:100" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- JS-->
<!-- [if lt IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js" type="text/javascript"></script><![endif] -->
<script src="https://ebury-chameleon.s3.amazonaws.com/1.17.0/scripts/ebury-chameleon.js" type="text/javascript"></script>
</head>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="/">
<img src="{{ url_for('static', filename='img/Ebury.png') }}" width="80" height="30" alt="">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-item nav-link active" href="/"><b>Default Scorer</b> <span class="sr-only">(current)</span></a>
</div>
<div class="navbar-nav ml-auto">
<a class="nav-item nav-link" href="/logout">Log out</a>
</div>
</div>
</nav>
<body>
</body>
</html>
index.html(only relevant parts its got a lot of forms)
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block content %}
<div class="m-1 pb-3"></div>
<div class="container-fluid">
<div class = "row">
<div class="col-md-3 push-md-3">
<div class = "m-0 pb-0">
<form action="" method="post" role="form" class="needs-validation" novalidate>
<div class="container">
<div class = "form-group">
<div class = "row">
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<span class = "input-group-text">BVD ID Number</span>
</div>
<input type = "text" class = "form-control" id = "bvd_id_number" name = "bvd_id_number">
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
{% endblock %}
error.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ERROR</title>
</head>
<body>
<h1>ERROR</h1>
</body>
</html>
So what happens is that the form doesnt appear and it seems only base.html appears with nothing else, the icon doesnt appear either but I tried commenting that out and that doesnt work.
The error printed is "404 Not Found: The requested URL was not found on the server. IF you entered the URL manually please check your spelling and try again"
To future people: I solved because the base.html did not specify where it had to be extended. The correct base.html code would be:
<html>
<head>
<meta charset="utf-8">
<title>Default Scorer -- Ebury</title>
<meta name = "viewport" content = "width=device-width", initial-scale = 1, shrink-to-fit=no">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}">
<!-- CSS-->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<link href="https://fonts.googleapis.com/css?family=Roboto:100" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- JS-->
<!-- [if lt IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js" type="text/javascript"></script><![endif] -->
<script src="https://ebury-chameleon.s3.amazonaws.com/1.17.0/scripts/ebury-chameleon.js" type="text/javascript"></script>
</head>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="/">
<img src="{{ url_for('static', filename='img/Ebury.png') }}" width="80" height="30" alt="">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-item nav-link active" href="/"><b>Default Scorer</b> <span class="sr-only">(current)</span></a>
</div>
<div class="navbar-nav ml-auto">
<a class="nav-item nav-link" href="/logout">Log out</a>
</div>
</div>
</nav>
<body>
{% block content %}
{% endblock %}
</body>
{% block scripts %}
{% endblock %}
</html>```
i Have python server with flask running on it
from flask import Flask,render_template
app = Flask(__name__)
#app.route("/")
def main():
return render_template('index.html')
if __name__ == ("__main__"):
app.run(debug = True, host = "0.0.0.0", port =80)
this is index.html there is simple form and send button
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>whatl0ol</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<div class="login">
<div class="heading">
<h2></h2>
<form action="#">
<div class="input-group input-group-lg">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input type="text" class="form-control" placeholder="">
</div>
<button type="submit" class="float">check</button>
</form>
</div>
</div>
</body>
</html>
i need solution to when user sends from index page, take it from python send to API.
need advices about site bandwith also.
thanks
make sure you have css files at this path
/your-project/static/css/style.css
also change your css in template to load it from static folder
<link href="{{ url_for('static', filename='css/style.css') }}" />
I am trying to dispaly a folium map in a flask web page which consists of a form containing 2 bootstrap selects and a submit button. The form elements work fine before the map is loaded. But when the map is loaded selects are not clickable.
This is my python script
from flask import Flask, render_template, request
import folium
app = Flask(__name__)
#app.route("/home")
def home():
return render_template("home.html")
#app.route("/result", methods =['POST'])
def result():
map = folium.Map(location=[53.3975054,-10.1987964], zoom_start =9, tiles ='Stamen Terrain')
map.save(outfile='templates/countries.html')
return render_template("result.html")
if __name__=="__main__":
app.run(debug = True)
home.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-responsive.min.css')}}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/font-awesome.min.css')}}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css')}}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/sl-slide.css')}}">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
</head>
<body>
<section id="about-us" class="container main">
<div class="row-fluid">
<div class="span8" >
<div class="blog">
<div class="blog-item well">
<h2>Heading2</h2>
<form action="{{ url_for('home') }}" method="POST">
<div class="form-group">
<select class="selectpicker" name="select_country" data-live-search="true" data-style="btn-primary">
<option >Country1</option>
<option >Country2</option>
</select>
<select class="selectpicker" name="select_event" data-live-search="true" data-style="btn-primary">
<option >Event1</option>
<option >Event1</option>
</select>
<input type="submit" class="btn btn-info" value="Submit Button">
</div>
</form>
</div>
</div>
</div>
</div>
</section>
{%block content%}
{%endblock%}
</body>
</html>
result.html
{%extends "home.html"%}
<div>
{%block content%}
{%include "countries.html"%}
{%endblock%}
</div>
How can I fix this?
It worked when i used an iframe inside the html file to display the map.