This is the error :
127.0.0.1 - - [22/Jun/2015 17:15:21] "POST /cgi-bin/get_tran_data.py HTTP/1.1" 2
00 -
127.0.0.1 - - [22/Jun/2015 17:15:21] command: C:\Python34\python.exe -u C:\Pytho
n34\ProjectShivam\webapp\cgi-bin\get_tran_data.py ""
127.0.0.1 - - [22/Jun/2015 17:15:22] b'Traceback (most recent call last):\r\n F
ile "C:\\Python34\\ProjectShivam\\webapp\\cgi-bin\\get_tran_data.py", line 20, i
n <module>\r\n with open("C:\\Python34\\ProjectShivam\\webapp\\cgi-bin\\tran_
add_success.py") as g:\r\nOSError: [Errno 22] Invalid argument: \'C:\\\\Python34
\\\\ProjectShivam\\\\webapp\\\\cgi-bin\\tran_add_success.py\'\r\n'
127.0.0.1 - - [22/Jun/2015 17:15:22] CGI script exit status 0x1
get_tran_data.py:
import cgi
import yate
import sqlite3
import sys
connection = sqlite3.connect('users.sqlite')
cursor = connection.cursor()
print('Content-type:text/html')
form=cgi.FieldStorage()
doctype=form['doctype'].value
docno=form['docno'].value
docdate=form['docdate'].value
bincard=form['bincard'].value
rate=form['rate'].value
quantity=form['qty'].value
cursor.execute("INSERT INTO TRAN(DOCTYPE,DOCNO,DOCDATE,BINCARD,QTY,RATE) VALUES (?,?,?,?,?,?)",(doctype,docno,docdate,bincard,rate,quantity))
connection.commit()
with open("C:\Python34\ProjectShivam\webapp\cgi-bin\tran_add_success.py") as g:
code = compile(g.read(),"tran_add_success.py", 'exec')
exec(code)
When i remove the open statement from get_tran_data.py, the script runs successfully. I used a similar open statement in another script and that ran successfully but here i don't know what is the problem?
EDIT:
This is get_opb_data.py, the script with similar code but runs successfully:
import cgi
import yate
import sqlite3
import sys
connection = sqlite3.connect('users.sqlite')
cursor = connection.cursor()
print('Content-type:text/html')
form=cgi.FieldStorage()
bincard=form['bincard'].value
desc=form['desc'].value
loc=form['loc'].value
qty=form['qty'].value
rate=form['rate'].value
Value=form['value'].value
currate=form['currate'].value
curqty=form['curqty'].value
cursor.execute("INSERT INTO OPB(Bincard,Description,Location,Quantity,Rate,Value,CurRate,CurQty) VALUES (?,?,?,?,?,?,?,?)",(bincard,desc,loc,qty,rate,Value,currate,curqty))
connection.commit()
with open("C:\Python34\ProjectShivam\webapp\cgi-bin\opb_add_success.py") as f:
code = compile(f.read(), "opb_add_success.py", 'exec')
exec(code)
Also, the tran_add_success.py file exists, I have made sure of that. I don't get why this is happening, that once script is running just fine and the other isnt.
tran.html:
<html>
<head>
<title>Transaction</title>
<link type="text/css" rel="stylesheet" href="coach.css" />
</head>
<body>
<img src="images/logo-cel-transparent_0.png" width="74" height="64"><strong><img src="images/logo-cel-transparent_0.png" alt="Cel logo" width="74" height="64" align="right">
</strong>
<h1 align="center"><strong>Central Electronics Limited</strong></h1>
<p> </p>
<h2 align="center">Storage Management System</h2>
<p> </p>
<div align="center"><strong>Transaction!!</strong></div>
<p align="left"> </p>
<p align="center">
<form action="cgi-bin/get_tran_data.py" method="post">
<div align="center">DocType :
<input type="text" name="doctype">
DocNo :
<input type="text" name="docno">
DocDate :
<input type="text" name="docdate">
<br><br>
BinCard :
<input type="text" name="bincard">
Rate :
<input type="text" name="rate">
Quantity :
<input type="text" name="qty">
<br>
<p align="center"><input type="submit" value="Submit"></p>
</div>
</form>
</p>
</body>
</html>
When i click the submit button on tran.html, the get_tran_data.py runs. Now it fetches the data from the form and saves it to database. I use open statement in get_tran_data.py so as to run another script which displays a success message on the screen.
Related
I am trying to run a c++ executable from a flask application.
I created two input for the arguments and one button to submit and run the executable.
What I want to execute is this command line: ./Ex02_DriveStatus 5 blablabla.sw
The executable Ex02_DriveStatus is on the same folder than the python file.
When I run it from the terminal ./Ex02_DriveStatus 5 blablabla.sw
it's working well.But I would like to be able to run it from my flask application/ web interface.
Here is my python code:
import canopen
from datetime import datetime
import time
import os
import numpy as np
import argparse
from DriveLib import Drive
from flask import Flask
from flask import request
from flask import render_template
import subprocess
from subprocess import PIPE
# os.system("sudo ifconfig can0 down")
# os.system("sudo ip link set can0 type can bitrate 500000")
# os.system("sudo ifconfig can0 up")
app = Flask(__name__)
#app.route('/')
def home():
return render_template('flashing.html')
#app.route('/flashing/')
def home_flash():
return render_template('flashing.html')
#app.route('/flashing/', methods=['POST'])
def flash():
global node_id
global file_name
node_id = request.form['node_id']
file_name = request.form['file_name']
if request.form.get("submit"):
node_id = request.form['node_id']
file_name = request.form['file_name']
if node_id == '':
node_id = 0
if file_name == '':
file_name = 0
if request.method == 'POST':
output = run(node_id, file_name)
return render_template('flashing.html', output=output, node_id=node_id, file_name=file_name)
def run(node_id, file_name):
s=subprocess.run(["./Ex02_DriveStatus", node_id, file_name],stdout=PIPE)
print(s)
return s.stdout.decode("utf-8")
And my HTML code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href='/static/main.css'/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type=text/javascript src="{{
url_for('static', filename='main.js') }}"></script>
<script>
window.addEventListener("load", function(){
// BASIC
numpad.attach({target: "demoA"});
// WITH OPTIONS
numpad.attach({target: "demoB"});
numpad.attach({target: "demoC"});
});
</script>
<title>FLASH the drive</title>
<p class="title"><strong>FLASH THE DRIVE</strong></p>
</head>
<body>
<div id="menu">
<ul id="onglets" >
<li class="active"> Flash drive </li>
<li> Test drive </li>
<li> Test module </li>
</ul>
</div>
<div class="content">
<!--test form-->
<form method="post" action="/flashing/">
<textarea id="output" name="output" rows="30" cols="50" style="resize:none" placeholder="//Your output here.">{{output}}</textarea><br>
<table>
<tr>
<td> <p>Chose the ID you want to flash with:</p> </td>
<td> <input name="node_id" id="demoA" style="height:50px;"> </td>
</tr>
<tr>
<td> <p>File name:</p> </td>
<td> <input name="file_name" style="height:50px;"> </td>
</tr>
<tr>
<td> <input id="buttonid" type="submit" name="submit" class="submit" value="FLASH"> </td>
</tr>
</table>
</form>
</div>
</body>
</html>
When I try this flask run it's running for ever without results.
I tried to create a python file test.py with just a print print("hello").
I assume this line is the problem:
s=subprocess.run(["./Ex02_DriveStatus", node_id, file_name],stdout=PIPE)
so I tested it with a simple file (the test.py):
s=subprocess.run(["python", file_name],stdout=PIPE)
and on the file_name input I would enter test.py and it is working.
So I don't know if it is because the executable from c++ gives me some conflict or if there is something I didn't write well.
Make sure your program is outputting to STDOUT.
Try removing the stdout=PIPE or try piping STDERR as well.
so far this is what I came up with
#html ask user to input information including an image
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="name" placeholder="name" type="text">
</div>
<div class="form-group">
<input class="form-control" name="subject" placeholder="subject" type="text">
</div>
<div class="form-group">
<input class="form-control" name="experience" placeholder="experience" type="text">
</div>
<div class="form-group">
<input class="form-control" name="phone" placeholder="puone-number" type="number">
</div>
<div class="form-group">
<input type="file" name="pic" id="pic">
</div>
<button class="btn btn-primary" type="submit">Register</button>
</form>
flask
#app.route("/register", methods=["GET", "POST"])
def register():
"""Show teacher registering menu"""
if request.method == "GET":
return render_template("register.html")
else:
# get the user input
name = request.form.get("name")
sub = request.form.get("subject")
exp = request.form.get("experience")
phone = request.form.get("phone")
f = request.files['pic']
pic = f.save(secure_filename(f.filename))
if not name or not sub or not exp or not phone:
return "404"
# insert in the database
sql = "INSERT INTO teachers (name, sub, exp, phone, pic) VALUES (?, ?, ?, ?, ?)"
db.execute(sql, name, sub, exp, phone, pic)
# inform the user for the success of the process
return render_template("success.html")
showing the results on html
<div>
{% for i in query %}
<div class="media bg-primary text-white">
<img class="align-self-end mr-3" src={{ i['pic'] }} alt="Generic placeholder image">
<div class="media-body">
<h5 class="mt-0">Mr. {{ i['name'] }}</h5>
<ul class="list-group list-group-flush text-dark">
<li class="list-group-item">subject: {{ i['sub'] }},</li>
<li class="list-group-item">experience: {{ i['exp'] }},</li>
<li class="list-group-item">Contact number: {{ i['phone'] }}</li>
</ul>
</div>
</div>
<br>
{% endfor %}
</div>
but right now every time I try it I find the value of the image column in my sql table to be NULL.
How can I fix that
pic = f.save(secure_filename(f.filename))
The save method returns None, so here pic will be None.
I think you intended to write its filename to the database, so perhaps change this to:
pic = secure_filename(f.filename)
f.save(pic)
Now pic is the filename on your server, so you just need to reconstruct this wherever the file is viewed.
Of course be aware that this uses the filename of the file which was uploaded by the user. You may wish to avoid this, incase of duplicates or just for cleanliness. See this other answer I wrote regarding that.
EDIT: Regarding your template.
When it comes to loading the picture in the template, let's assume the filename came through as image.jpg, and you use your exisiting code:
<img src={{ i['pic'] }}>
You could view the source of the rendered page, and see:
<img src=image.jpg>
Two problems with this:
that attribute should have quotes (<img src="image.jpg">)
that's trying to load the file from whichever path is rendered in the browser, so if the URL was http://example.com/subdir/ it's looking for the image at http://example.com/subdir/image.jpg. This can also be verified in the Network tab of your browsers dev tools.
The solution, build the URL with flask's url_for function:
<img src="{{ url_for('static', filename=i['pic']) }}">
This, of course, assumes that you've saved the file to the static directory on your server. You may wish to ensure this in the python code:
import os
# ...
pic = secure_filename(f.filename)
f.save(os.path.join('static', pic))
I'm new to Python and trying to develop simple web application.
In the code below I am trying to retrieve values from DB and rending on HTML page
I'm able to see the HTML page but not values passed. Please help me here.
Python code
#app.route('/userDetails', methods=['POST', 'GET'])
def userDetails():
if request.method == 'POST':
print('in get method')
userid = request.form['userId']
print('user id ', userid)
conn = mysql.connect()
cursor = conn.cursor()
# Get User Details
print('execut sql')
result = cursor.execute("SELECT * FROM tbl_user WHERE user_id= %s", [userid])
if result > 0:
data = cursor.fetchall()
for row in data:
userId = row[0]
name = row[1]
userName = row[2]
password = row[3]
return render_template("userDetails.html", userId=userId, name=name, userName=userName, password=password)
else:
return render_template('index.html')
cursor.close()
HTML code below.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<title>Python Flask Bucket List App</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h3 class="text-muted">Python Flask App </h3>
</div>
<div class="jumbotron">
<h1>Display User Details</h1>
<div class="jumbotron">
<form class=class="form-userDetails, action="/userDetails", method="POST">
User ID:<input type="text" name="userId" class="form-control">
Name <output name="name" id="name" for="userId" class="form-control"></output>
User Name <output name="userName" id="userName" for="userId" class="form-control"></output>
Password <output name="password" id="password" for="userId" class="form-control"></output>
</br>
<button id="btnretive" class="btn btn-lg btn-primary btn-block" type="submit">Retrive</button>
</form>
</div>
<div class="Footer">
<footer class="footer">
<p>© Company 2015</p>
</footer>
</div>
</div>
</body>
</html>
#DRaj, you are using <output> tag in incorrect way. From the specification,
The HTML Output element () is a container element into which a site or app can inject the results of a calculation or the outcome of a user action.
For more info and example refer to this Mozilla page.
Now,
Flask uses Jinja2 template engine for its HTML rendering. So, the correct way to output values would be to enter a python variable inside Expression delimiters {{ ... }} in the HTML and pass the variables to render_template method.
i.e.
<form class=class="form-userDetails, action="/userDetails", method="POST">
User ID:<input type="text" name="userId" class="form-control">
Name: {{ name }}
User Name: {{ userName }}
Password: {{ password }}
</br>
<button id="btnretive" class="btn btn-lg btn-primary btn-block" type="submit">Retrive</button>
</form>
and the python code should be:-
return render_template("userDetails.html", name=name, userName=userName, password=password)
Refer to this Jinja template designer documentation for more information.
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.
I need help, I have a Python script that do some work and print html web page.
I need to pass string from that outputed web page to that script.
Is that possible ?
In future I want to use radio buttons where user will thick data for plotting from predefinned ones.
Thanks for any advice...
My code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
import cgitb
cgitb.enable()
import subprocess
import os
print "Content-type: text/html\n\n";
web = """
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
</head>
<body>
<div id='wrapper'>
<div id='header'>
</div>
<div id='content'>
<div class='content'>
<div><h3>GRAPH</h3></div>
<br>
<div style='height:520px;width:1000px;overflow:scroll;overflow-x:auto;overflow-y:hidden;'>
<img src='http://localhost/steps.png' alt='image' />
</div>
<br>
<button onclick="myFunction()">REFRESH</button>
<script>
function myFunction() {
location.reload();
}
</script>
<br>
<form action='/cgi-bin/test.py' method='post'>
nazov suboru: <input type='text' data='data'> <br />
<input type='submit' value='Submit' />
</form>
</div>
</div>
</div>
</body>
</html>
"""
print web
proc = subprocess.Popen(['gnuplot','-p'],
shell=True,
stdin=subprocess.PIPE,
)
proc.communicate("""
reset
set terminal pngcairo enhanced size 3000,500 font 'Arial,11' rounded;
set output '/opt/lampp/htdocs/%s.png'
set datafile separator "|"
plot \
\
'%s.txt' u 0:3 sm cs w l ls 1 t 'X-suradnice',\
'%s.txt' u 0:4 sm cs w l ls 2 t 'Y-suradnice',\
'%s.txt' u 0:5 sm cs w l ls 3 t 'Z-suradnice'
"""%(data,data,data,data))
Your question is quite hard to understand, but I think you are trying to work out how to access the data parameter submitted by the form POST. You can do that with the cgi module:
import cgi
form = cgi.FieldStorage()
data = form.getvalue('data')