How do I write an app.yaml file for a particular Python app I'm trying to put on Google App Engine?
Here is the simple python code I'm trying to work on:
import webapp2
form="""
<form action="http://www.google.com/search">
<input name="q">
<input type="submit">
</form>
"""
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.out.write(form)
app=webapp2.WSGIApplication([('/',MainPage)],
debug=True)
Now whenever I'm trying to run it on Google App Engine, it simply doesn't work. Shows nothing on localhost and shows server error while deploying it.
Here is the app.yaml code:
application: saaps-2012
version: 1
runtime: python
api_version: 1
handlers:
- url: /.*
script: program.py
Try to add the following lines in the end of your file program.py:
def main():
app.run()
if __name__ == "__main__":
main()
Your file should then look like something like this:
import webapp2
form="""
<form action="http://www.google.com/search">
<input name="q">
<input type="submit">
</form>
"""
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.out.write(form)
app=webapp2.WSGIApplication([('/',MainPage)],
debug=True)
def main():
app.run()
if __name__ == "__main__":
main()
Have a try and let me know about your results.
Related
I'm completely new to flask, and really am completely lost with how to approach this. I've looked into other SO questions but I can't seem to get this working regardless.
I have a form as such:
<form class="teamSelection" method="POST" action="/submitted">
<select class="teamForm" id="teamDropdownSelector" type="text" name="teamDropdown" placeholder="Select A Team">
<option disabled selected>Select a game</option>
<option id="WatfordVSManchester Utd" value="">Watford VS Manchester Utd</option>
</select>
<input class="btn" type="submit" value="submit">
</form>
and my flask as so:
from flask import Flask
app = Flask(__name__)
#app.route("/submitted")
def hello():
return "hello world"
The goal is to take the content of the selected/submitted dropdown item, pass this to the flask file where I then use the team names to scrape information about the match. However at the moment I can't even seem to get the POST of the form to work and am at a complete loss. I appreciate this is a pretty vague and open-ended question, but I seriously don't know how else to figure this out.
Should I instead use jquery to detect when the dropdown has changed and use AJAX to send a POST to somehow call the script and pass the values into it?
Any help would be greatly appreciated.
EDIT
I thought I put this in the original post, but must have forgot.
I am currently running an apache localhost server, and am working with flask via pycharm. All I've done at the moment is install the flask package in pycharm, and haven't set any of it up like I've seen in some tutorials do when running from the command line. I assumed this step wasn't necessary, as I already have a server up and running with apache?
When it comes to backend stuff like this I really have no idea, so apologies if that's a stupid assumption.
I've changed the flask to:
from flask import Flask
app = Flask(__name__)
#app.route("/submitted", methods=['POST'])
def hello():
with open("newTest.csv", mode="w+") as file:
fileWriter = csv.writer(file)
fileWriter.writerow(['Time', 'HomeTeam', 'AwayTeam'])
file.close()
The reason being as I can see if this script is actually being called, if it is it will make a new csv file called newTest. After running the webpage and submitting no new csv file appears, so this script isn't being run, meaning it's likely due to me not configuring flask correctly?/The assumption that apache was enough was incorrect?
You have just to tell the flask method to accept POST request and to read parameters from the request
Example:
from flask import Flask, request
app = Flask(__name__)
#app.route("/submitted", methods=['POST'])
def hello():
myvariable = request.form.get("teamDropdown")
... your code ...
return "hello world"
So, your question is not about flask, but about fopen - you have to add a full file path including directory path script_dir = path.dirname(path.abspath(__file__)).
Flask script (modified for launching in my local copy of project):
from flask import Flask, render_template, request
import csv
from os import path
app = Flask(__name__)
script_dir = path.dirname(path.abspath(__file__))
#app.route ("/")
def index():
return render_template("index.html")
#app.route("/submitted", methods=["GET", "POST"])
def hello():
if request.method == "GET":
return render_template("index.html")
filefullpath = script_dir + '//newTest.csv'
with open(filefullpath, mode="w+") as file:
fileWriter = csv.writer(file)
fileWriter.writerow(['Time', 'HomeTeam', 'AwayTeam'])
file.close()
return "hello world"
index.html (in folder "/templates")
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Test
<br>
<form class="teamSelection" method="POST" action="/submitted">
<select class="teamForm" id="teamDropdownSelector" type="text" name="teamDropdown" placeholder="Select A Team">
<option disabled selected>Select a game</option>
<option id="WatfordVSManchester Utd" value="">Watford VS Manchester Utd</option>
</select>
<input class="btn" type="submit" value="submit">
</form>
</body>
</html>
Modify your code as:
from flask import Flask
app = Flask(__name__)
#app.route("/submitted", methods=['POST'])
def hello():
return request.form['teamDropdown']
Please let me know if that helps.
How can I call a python script when the button is html file is clicked?
I am trying to change the language of the website by clicking the button. This is what I have done so far, but I am getting an error when I hit the button "page not found" and "The current URL, foo, didn't match any of these." What am I doing wrong
login.html
<form action="/foo" method="post">
<input type="submit" name = "first_button" value="French">
<input type="submit" name = "second_button" value="Spanish">
</form>
views.py
from app import foo
def get_language_from_client(request):
new_lang= foo()
if new_lang=="fr":
client_lang="fr"
else:
client_lang = translation.get_language_from_request(request)
print "client_lang:", client_lang
if "en" in client_lang:
return 0
elif "nl" in client_lang:
return 1
elif "fr" in client_lang:
return 2
elif "pl" in client_lang:
return 3
elif "ru" in client_lang:
return 4
else:
print "Unknown language code:", client_lang
return 2
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('login.html')
#app.route('/foo')
def foo():
return "fr"
if __name__ == '__main__':
app.run()
My directory structure looks like
scriboxapp
-templates
-login.html
-views.py
-app.py
I would recommend using Flask for this.
Here's an example of what you can do:
index.html:
<form action="/foo" method="POST">
<input type="submit" value="French">
</form>
app.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/foo', methods=['GET', 'POST'])
def foo():
'''execute whatever code you want when the button gets clicked here'''
return
if __name__ == '__main__':
app.run()
When you run your app.py file and navigate to the URL where the Flask webserver is running, which in this case is localhost, you will be presented with the index.html file.
In the above example, you can see that the button containing the value French will execute your /foo route. Your function with the proper route decorator /foo is where you can execute your desired code.
To get this working, your directory structure should look something like this:
- app
- templates
- index.html
- app.py
I am trying to read and print a file in Google App Engine, but the code bellow seems unresponsive. I can upload the file, and my expectation was that it would just print the text, but it does nothing. I thought about adding a submit button, but I have no idea how to link submit with pythons printing. How can I get this to print on command?
I have seen the example provided by GAE here, but I would first like to keep it all on one page, and second I still don't understand how the submit calls that second page.
import webapp2
from google.appengine.ext.webapp import util
class MainPage(webapp2.RequestHandler):
#http://bukhantsov.org/2011/12/python-google-app-engine-calculator/
def get(self):
# build a list of operations
self.response.out.write("""<html>
<body>
<form action='/' method='get' autocomplete='off'>
<input type='file' name='file'/><br/>
#<input type='submit' name="test" value="submit">
</form>
</body>
</html>""")
file = self.request.get('file')
self.response.out.write(file)
app = webapp2.WSGIApplication([('/', MainPage)], debug=True)
def main():
util.run_wsgi_app(app)
if __name__ == '__main__':
main()
Your form is sent using the HTTP GET method, but for file uploads you need POST. Change it from:
method='get'
to:
method='post'
You will also need to handle POST requests in a different method. The POST body itself should be available as self.request.POST. So you end up with something like:
def post(self):
file = self.request.POST['file']
self.response.out.write(file)
I am trying to upload a file but the browser spinner rolls forever, server logs don't show updates and the file doesn't get uploaded. It sure is a newbie error but I have no clue what that is:-
static/index.html :-
html
form action="http://127.0.0.1:5000/upload" method="post" enctype="multipart/form-data"
input type="file" name="db"/
input type="submit" value="upload"/
/form
html
app.py
from flask import Flask
from flask import request
from werkzeug import secure_filename
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
#app.route('/upload', methods=['GET', 'POST'])
def upload_file():
print 'upload_file'
if request.method == 'POST':
print 'post'
f = request.files['db']
f.save(secure_filename(f.filename))
if __name__ == '__main__':
app.run(debug=True)
Thanks
Env: Flask 0.9, Jinja2-2.6 and Werkzeug-0.8.3 with Python 2.7 on Win7 x64 with IE9 and Chrome
The docs say you should use enctype="multipart/form-data".
Also, I might try method="POST" (uppercase), if only because defensive coding is a good habit, the defensive maneuver here being not assuming that Flask is bug-free.
I'm trying to do a simple echo app using Python. I want to submit a file with a POST form and echo it back (an HTML file).
Here's the handlers section of the YAML I'm using:
handlers:
- url: /statics
static_dir: statics
- url: .*
script: main.py
It's basically the hello world example in main.py and I added a directory to host my static html form file. Here's the HTML in statics/test.html:
<form action="/" enctype="multipart/form-data" method="post">
<input type="file" name="bookmarks_file">
<input type="submit" value="Upload">
</form>
The handler looks like this:
#!/usr/bin/env python
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write(self.request.get('bookmarks_file'))
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
However, I'm getting an error 405 when posting the file. How come?
You are submitting your form with the POST method, but you implemented a get() handler instead of a post() handler. Changing def get(self): to def post(self): should fix the HTTP 405 error.