I'm trying to create a webserver with micropython in access point (hotspot) mode. My problem is that I don't know how to pass simple HTML user input to a python variable (username and password).
Flask/MicroWebSrv is not an option for me due to memory issues (using an ESP8266 with limited flash and RAM) and I don't really want to rebuild my webserver from scratch. Previous solutions based on CGI package is depreciated. Any other generic method?
import network
import socket
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid=ap_ssid, password=ap_psw)
s = socket.socket()
s.bind(('', 80))
s.listen(5)
def webpage():
html = """
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1", charset="UTF-8">
<title>Login Form</title>
</head>
<body>
<div class="center">
<div class="header">
Login Form
</div>
<form method="post">
<input type="text" placeholder="Username" id="wifi_ssid" name="wifi_ssid">
<i class="far fa-envelope"></i>
<input id="wifi_psw" name="wifi_psw" type="password" placeholder="Password">
<i class="fas fa-lock" onclick="show()"></i>
<input type="submit" value="Sign in">
</form>
</div>
</body>
</html>"""
return html
while True:
conn, addr = s.accept()
request = conn.recv(1024)
response = webpage()
conn.send(response)
conn.close()
Related
I built the interface of a python script that sends sms using an api, it works normally but quad I try to send a message from the interface nothing happens, here is my code
This is main.py file
import eel
import os
from twilio.rest import Client
dirname = os.path.dirname('/Users/Admin/Desktop/App/')
eel.init(os.path.join(dirname,'web/'))
#eel.expose
def send_message(number, receiver, message):
# send sms
account_sid = ''
auth_token = ''
client = Client(account_sid, auth_token)
message = client.messages.create(from_=number, body=message, to=receiver)
print(message.sid)
eel.start('index.html')
script.js
document.getElementById("btn").addEventListener("click", function() {
var name = document.getElementById("number").value;
var email = document.getElementById("receiver").value;
var message = document.getElementById("message").value;
send_message(number, receiver, message);
});
function send_message(number, receiver, message) {
eel.send_message(number, receiver, message)(function(result) {
console.log(result);
});
}
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>App</title>
</head>
<body>
<div class="form">
<form onsubmit="eel.send_message(this.number.value, this.receiver.value, this.message.value); return false;">
<input type="number" name="name" id="number" placeholder="your number" required>
<input type="number" name="number" id="receiver" placeholder="Receiver" required>
<textarea name="message" id="message" cols="30" rows="10" placeholder="Enter message" required></textarea>
<input type="submit" value="Send" id="btn">
</form>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
I am trying to build an application that allows me to send sms from an interface using the eel framework
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
I am completely new to python and Flask and I am trying to run in my computer the code showed in this page:
http://runnable.com/UhLMQLffO1YSAADK/handle-a-post-request-in-flask-for-python
This are the steeps I follow and the code:
1-I have installed Flask
2-Files
File app.py
# We need to import request to access the details of the POST request
# and render_template, to render our templates (form and response)
# we'll use url_for to get some URLs for the app on the templates
from flask import Flask, render_template, request, url_for
# Initialize the Flask application
app = Flask(__name__)
# Define a route for the default URL, which loads the form
#app.route('/')
def form():
return render_template('form_submit.html')
# Define a route for the action of the form, for example '/hello/'
# We are also defining which type of requests this route is
# accepting: POST requests in this case
#app.route('/hello/', methods=['POST'])
def hello():
name=request.form['yourname']
email=request.form['youremail']
return render_template('form_action.html', name=name, email=email)
# Run the app :)
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=int("80")
)
File form_action.html
<html>
<head>
<title>Handle POST requests with Flask</title>
<link rel=stylesheet type=text/css href="style.css">
</head>
<body>
<div id="container">
<div class="title">
<h1>POST request with Flask</h1>
</div>
<div id="content">
Hello <strong>{{name}}</strong> ({{email}})!
</div>
</div>
</div>
</body>
</html>
File form_submit.html
<html>
<head>
<title>Handle POST requests with Flask</title>
<link rel=stylesheet type=text/css href="style.css">
</head>
<body>
<div id="container">
<div class="title">
<h1>POST request with Flask</h1>
</div>
<div id="content">
<form method="post" action="{{ url_for('hello') }}">
<label for="yourname">Please enter your name:</label>
<input type="text" name="yourname" /><br />
<label for="youremail">Please enter your email:</label>
<input type="text" name="youremail" /><br />
<input type="submit" value="Send" />
</form>
</div>
</div>
</div>
</body>
</html>
3-I run the py file:
sudo python app.py
[sudo] password for jose:
* Running on http://0.0.0.0:80/ (Press CTRL+C to quit)
When I open the browser I write:
file:///home/jose/Escritorio/python/app/form_submit.html
I insert the data in the 2 forms and I press Send and this is what happens:
URL: file:///home/jose/Escritorio/python/app/{{url_for('hello')}}
Web Page: File not found
What am I doing wrong?
0.0.0.0 means that you can access the flask website from outside of the website host. Use the host ip plus the port # you specified
http://:80/hello in your case. That should display the form_action.html you specified in your routes.
If you want save form data, your code didn't work. You must have a database or save in a file.
Using Flask and SQLAlchemy on my localhost, I am looking to be able to submit a simple contact form and, using AJAX, pass the submitted data along to my Flask API and then insert it into my local database, named contact.db.
To set up my database, I put together a script named setup.py, which successfully creates a database in my working directory. Its contents look as follows:
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
engine = create_engine('sqlite:///contact.db', echo=True)
Base = declarative_base()
########################################################################
class Contact(Base):
""""""
__tablename__ = "contact"
id = Column(Integer, primary_key=True)
f_name = Column(String)
l_name = Column(String)
email = Column(String)
message = Column(String)
#----------------------------------------------------------------------
def __init__(self, f_name, l_name, email, message):
""""""
self.f_name = f_name
self.l_name = l_name
self.email = email
self.message = message
# create tables
Base.metadata.create_all(engine)
My simple contact page collects the data and submits it to my flask route /contact/request using AJAX (I have confirmed this to work via the console). For reference, however, here is the code I use in contact.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">
<title>Contact</title>
<!-- Bootstrap -->
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
<script>
$(document).ready(function(){
$("#submitForm").click(function()
{
var firstName = $("#f_name").val();
var lastName = $("#l_name").val();
var email = $("#email").val();
var mess = $("#mess").val();
var nud = {
"f_name" : firstName,
"l_name" : lastName,
"email" : email,
"message" : mess
}
$.ajax({
type: "POST",
url: "/contact/request",
data: JSON.stringify(nud, null, '\t'),
contentType: 'application/json;charset=UTF-8',
success: function(result) {
console.log(result);
}
})
});
})
</script>
</head>
<body>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<h1 style="text-align: center">Contact Me</h1>
</div>
<div class="panel-body">
<form role="form">
<div class="form-horizontal" class="form-group" style="width:50%">
<label for="name has-success">First Name</label>
<input class="form-control input-md" type="text" class="form-control" id="f_name" placeholder="Matthew">
</div><br />
<div class="form-horizontal" class="form-group" style="width:50%">
<label for="email">Last Name</label>
<input class="form-control input-md" type="text" class="form-control" id="l_name" placeholder="Gross">
</div><br />
<div class="form-horizontal" class="form-group" style="width:50%">
<label for="email">Email</label>
<input class="form-control input-md" type="email" class="form-control" id="email" placeholder="mattkgross#gmail.com">
</div><br />
<div class="form-group">
<label for="aboutMe">Message</label>
<textarea class="form-control" id="mess" placeholder="What's up?" rows="3" ></textarea>
</div>
<div>
<button type="button" input type "submit" class="btn btn-success" id="submitForm">Submit</button>
</div>
</form>
</div>
</div>
</div>
<div class="col-md-3"></div>
</div>
</body>
</html>
Finally, I have my actual Flask API script that I run in order to start up my service on localhost. The /contact route works fine. However, when I send the data via my form submission, I get an internal server error. This is undoubtedly being caused by my incorrect attempt at inserting the parsed JSON into my contact database. Below is the code used in my api.py:
from flask import Flask
from flask import request
from flask import render_template
import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from setup import Contact
app = Flask(__name__)
#app.route('/contact')
def contact():
return render_template('contact.html')
#app.route('/contact/request', methods=["POST"])
def contact_request():
if request.method == "POST":
engine = create_engine('sqlite:///contact.db', echo=True)
# Create a Session
Session = sessionmaker(bind=engine)
session = Session()
new_contact = Contact(request.json['f_name'],
request.json['l_name'],
request.json['email'],
request.json['message'])
# Add the record to the session object
session.add(new_contact)
# commit the record the database
session.commit()
#return str(request.json)
app.debug = True
app.run()
If I comment out the two lines:
session.add(new_contact)
session.commit()
and replace them with return str(request.json), my console successfully returns the JSON I sent. I am just completely lost as to where I am going wrong in inserting my data into the database and why it is throwing an error at me for my attempt.
Any help you can give me would be very much appreciated - hopefully it's something simple I overlooked in being new to this whole thing. Thanks!
In flask you have to return something for your route otherwise it will lead to odd behavior. In your case you could return something as simple as an "OK" to let your AJAX know the function completed successfully.
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>