WSGI app can not receive post method from html form - python

hello I just started to program for the web with python without use of any web framework.
for testing reasons I created a simple html form with the post method to pass a simple text data to the WSGI app that I wrote.
this is the code for the HTML form:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<form action="/tester" method="post">
<input type="text" name="user">
<input type="submit" value="go">
</form>
</body>
</html>
and this is the code for the simple WSGI app:
def test_app(environ, start_response):
var1 = str(environ["REQUEST_METHOD"])
start_response('200 OK', [('Content-Type', 'text/plain')])
return[var1]
but no matter what I do it keeps showing me GET!(as the purpose of the code is tho return the method).
I don't know what I need to do?

Related

I have started learning flask and when I run my home.html and submit a form then it gives your files can't be accessed. For backend I have used flask

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.

How to build a get-form post in flask

Ok so I am new to flask, and want to know what objects or tools I would use to do this. I want to create a form, where the user inputs some text, clicks a submit button, then the text that they submitted is bound as a python string, and has a function run on it, and that text is then posted back onto the web page they are viewing with the return value of that function it went through. Here is an example:
html form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action = "/" method="get">
<input type="text" name="mail" size="25">
<input type="submit" value="Submit">
</form>
<textarea cols="50" rows="4" name="result"></textarea>
</body>
</html>
Then here is what I believe should be the url function should look like
#app.route('/', methods=['GET', 'POST'])
def form():
if request.method == 'GET':
input_text = request.data #step to bind form text to python string
new_text = textfunction(input_text) #running the function on the retrieved test.
return (new_text) # no idea if this is write, but returns text after modification.
What would be the best way to set this up? Would it be correct to put a variable as the value for the input html? Need some help on this.
Basically, what you want to do is have a block in your template that is only included if the variable has a value set. See the following example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action = "/" method="get">
<input type="text" name="mail" size="25">
<input type="submit" value="Submit">
</form>
{% if result %}
<textarea cols="50" rows="4" name="result">{{ result }}</textarea>
{% endif %}
</body>
</html>
and then in your python code
#app.route('/', methods=['GET', 'POST'])
def index(result=None):
if request.args.get('mail', None):
result = process_text(request.args['mail'])
return render_template('index.html', result=result)
def process_text(text):
return "FOO" + text

Python scripting

I have been following along in Programming Python 4th Edition. One of the tasks is to write a web page that uses cgi to call a python script. It all seems simple enough, but rather than run the script, the browser echos the script instead. I think it may be related to the shebang but I am not sure.
The HTML:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8" />
<title>Interactive Page</title>
</head>
<body>
<form method=POST action="cgi-bin/cgi101.py">
<p><b>Enter your name</b></p>
<p><input type=text name=user /></p>
<p><input type=submit title=Submit /></p>
</form>
</body>
</html>
The script:
#!python
import cgi
form = cgi.FieldStorage()
print('Content-type: text/html\n')
print('<title>Reply Page</title>')
if not 'user' in form:
print('<h1>Who are you?</h1>')
else:
print('<h1>Hello <i>%s</i></h1>' % cgi.escape(form['user'].value))
Instead of a new page showing "Hello Tim" I'm getting a new page with the script dumped into it.
This is an Apache configuration issue that I have not quite worked through. Now when I run it, I get a file not found error from Apache. Progress I guess...

How to use cgi form input as variable in call to system command in Python script?

Say I have a web page like this on an Ubuntu 12.04 web server running apache:
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Name Input</title>
</head>
<body>
<form action="./test.py" method="post">
<p> Name: <input type="text" name="name" id="name" value=""/></p>
<input type="submit" value="Submit" />
</form>
</body>
</html>
I want to use the value of name as input to a shell script which is called by a Python CGI script like this.
test.py:
#!/usr/bin/env python
import commands, cgi, cgitb
form = cgi.FieldStorage()
name = form.getvalue('name')
result = commands.getoutput("/usr/lib/cgi-bin/test.sh name")
contents = pageTemplate.format(**locals())
print "Content-type: text/html\n\n"
print contents
In the example code above, how should name be passed to test.sh?
For completeness, say that pageTemplate looks like this:
pageTemplate = '''<!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>Name Output</title>
</head>
<body>
{result}
</body>
</html>
'''
Just pass it into the command:
result = commands.getoutput("/usr/lib/cgi-bin/test.sh %s" % name)

Python CGI Script Not Executing

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.

Categories