I want to run a script when the button with the bottle is pressed. But I get 404 errors every time. It says localhost: //File.py in the address bar, but I don't know how to route it.
app.py
from bottle import *
#route('/')
def home():
return template('deneme.html')
run(host='localhost',port=8080)
File.py
#!/usr/bin/python
import cgi, cgitb
form = cgi.FieldStorage
username = form["username"].value
emailaddress = form["emailaddress"].value
print("Content-type: text/html\r\n\r\n")
print( "<html>")
print("<head>")
print("<title>First Script</tittle>")
print("</head")
print("<body>")
print("<h3>This is HTML's Body Section</h3>")
print(username)
print(emailaddress)
print("</body>")
print("</html>")
deneme.html
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="File.py" method="post">
username: <input type="text" name="username"/>
<br />
Email Adress: <input type="email" name="emailaddress"/>
<input type="submit" name="Submit">
</form>
</body>
</html>
You shouldn't use cgi and cgitb with Bottle, Flask, or any other Python web framework.
Try something like
from bottle import run, route, request
#route('/')
def home():
return template('deneme.html')
#route('/foo')
def foo():
return '%s %s' % (request.forms.username, request.forms.email)
run(host='localhost',port=8080)
(and change the action of your form to action="/foo").
Also, consider using Flask; it's in the same vein as Bottle, but more popular and more maintained.
Related
this is my rule.html
<!DOCTYPE html>
<html>
<head>
<title>rules</title>
</head>
<body>
<H1>Have fun and enjoy {{name}}</H1>
<p>So there are some rules that will help you to play this game.</p>
</body>
</html>
this one is home page html code. Please help, I saw tutorials but not getting anything.
<!DOCTYPE html>
<html>
<head>
<title> Home</title>
</head>
<body>
<h1>Welcome to guess the game!!</h1>
<form method="post" action="/rule">
<h3>So, what is your name":</h3>
<input type="text" name="user">
<input type="submit" value="submit" >
</form>
</body>
this one is my python code.
from flask import Flask,render_template, request, redirect, url_for
app= Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/rule', methods=["POST","GET"])
def rule():
if request.method=="POST":
user=request.form["user"]
print(user)
return redirect(url_for("user",usr=user))
else:
return render_template("rule.html")
#app.route("/<usr>")
def user(usr):
return render_template("rule.html",name=usr)
if __name__ == '__main__':
app.run(debug=True)
sorry for so many codes. but i need help.
and my os is window 8.1, python -> 3.7.1, flask->1.1.1,werkzeug->1.0.1
error page
When I look at your error page, your browser seems to try to access D:/rule - this should not be served by the file system, but by Flask.
You need to access your app e.g. as localhost:5000/home.html and then it should work.
For me it looks like you directly access the html file in your browser from the file system.
First, you need to run your app, with something like python main.py, where main.py is the file name of your app.
Then enter the URL, which you see in the console plus append the home.html - it should work then.
i have created a form for user input, and run it in app.py with flask. What i want to achieve is to be able to get the user data, and then save it to my mongodb database. This is my html for the form.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../static/Recording.css">
</head>
<div class="header">
<h1>Create a recording</h1>
</div>
<body>
<div class="create">
<form name="formdata">
<label for="trolley">Trolley</label>
<input type="text" id=trolley name="trolley" size="180" required>
<label for="datetime">Date & time</label><br>
<input type="datetime-local" id="datetime" name="datetime"><br required>
<label for="temp">Temperature</label>
<input type="text" id="temp" name="temp" size="180" required>
<input id="button1" type="submit" value="Record"">
</form>
<script src="https://cdn.jsdelivr.net/npm/papaparse#5.2.0/papaparse.min.js"></script>
<script src="../static/Recording.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="../static/database.js"></script>
</body>
</html>
This is my app.py file
from flask import Flask, render_template, jsonify, json, request
from flask_pymongo import PyMongo
from pymongo import MongoClient
app = Flask(__name__)
#routes
from q2 import subroutes
client = MongoClient("mongodb+srv://Stanislas:reddevils97#tma.p1mbs.mongodb.net/<dbname>?retryWrites=true&w=majority")
db = client.get_database("smarttrolley")
records = db.recordings
#app.route("/")
def home():
return render_template('SmartTrolley.html')
#app.route("/userinput/")
def userInput():
return render_template('Recording.html')
if __name__=='__main__':
app.debug = True
app.run(port=5000)
'''
this is my subroutes.py file, which handles the user data and post it in the route "/data"
from flask import Flask
from app import app
from q2.models import User
#app.route("/data", methods=["POST"])
def data():
return User().input()
This is my models.py file, which collects the data from the "/data" route, which then proceeds to insert the data into my mongoDB database.
from flask import Flask, jsonify, request
from app import db, records
class User:
def input(self):
inputs = {
"_id": "",
"trolleyname": request.form.get('trolley'),
"Date & Time": request.form.get('datetime'),
"Temperature": request.form.get('temp')
}
db.records.insert_one(inputs)
return jsonify(inputs), 200
I am using jquery ajax call for the data to be sent. I am able to receive the data via the console.log everytime the user submits data, and everything is working fine. However, i am receiving the error "GET http://localhost:5000/data 404 (NOT FOUND)", which shows that they can't locate my "/data" route. Is anyone able to help me and find out whats wrong, because i have done the importing of the subroutes into my app.py and nothing seems to be working. thank you
It is only allowed for POST method in your code
#app.route("/data", methods=["POST"])
def data():
return User().input()
#You are using GET method here
GET http://localhost:5000/data 404 (NOT FOUND)
Either change above code to following:
#app.route("/data", methods=["GET"])
def data():
return User().input()
#Or you can hit POST request
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 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.
Just doing a basic python project with HTML file, i came across a tutorial which gave an idea about how i can execute the code,
here is the HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Admin Login</title>
</head>
<body>
<big><big>Login
Here<br>
<br>
</big></big>
<form action="/var/www/cgi-bin/Login.py" name="LoginForm"><big>Administration
Login<br>
User Name<br>
<input name="UserName"><br>
<br>
<br>
Password<br>
<input name="PassWord"><br>
</big><br>
<br>
<br>
<input type="submit">
<br>
</form>
__ <br>
</body>
</html>
and the python code..
#!/usr/bin/python
import cgi
import cgitb; cgitb.enable()
# get the info from the html form
form = cgi.FieldStorage()
#set up the html stuff
reshtml = """Content-Type: text/html\n
<html>
<head><title>Security Precaution</title></head>
<body>
"""
print reshtml
User = form['UserName'].value
Pass = form['PassWord'].value
if User == 'Myusername' and Pass == 'MyPasword':
print '<big><big>Welcome'
print 'Hello</big></big><br>'
print '<br>'
else:
print 'Sorry, incorrect user name or password'
print '</body>'
print '</html>'
The problem is, when i submit the username and password, it just shows the whole code back on the browser and not the required Welcome message :(. I use Fedora13 .. can anyone tell me what is going wrong? I even changed the permissions of the file(s).
Most likely, your webserver is not configured to execute the script. Even if it's marked as 'executable' in the file system, that doesn't necessarily mean the webserver knows that it should be executing .py files (rather than just serving them 'straight up'). Have a look here if you're running Apache: http://httpd.apache.org/docs/2.0/howto/cgi.html
<form action="/var/www/cgi-bin/Login.py" name="LoginForm">
Try
<form action="/cgi-bin/Login.py" name="LoginForm">
/var/www is probably the path from your ftp site. The web server will only look inside /var/www, so it puts that part there automatically.