Python - Google App Engine - python

I'm just starting learning google app engine.
When I enter the following code below, all I got is "Hello world!"
I think the desired result is "Hello, webapp World!"
What am I missing? I even try copying the google framework folder to live in the same folder as my app.
Thanks.
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, webapp World!')
application = webapp.WSGIApplication(
[('/', MainPage)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()

Running exactly this code DOES give me the desired output. I suspect you must be erroneously running some other code, since there's absolutely no way this code as given could possibly emit what you observe.

Related

Run a dash app inside a flask

I want to be able to run my dash app from my flask app when I go to a specific url '/dash'. However I get the following error. 'TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.'
flaskapp.py
app = Flask(__name__)
#app.route('/')
def index():
return 'Welcome!'
#app.route('/dash')
def dash_chart():
dashapp.start() # Run the dash app
if __name__ == "__main__":
app.run(debug=True)
dashapp.py
def start():
app = dash.Dash()
app.layout = html.Div('Hello World')
if __name__=='__main__':
app.run_server(debug=True)
If I make the following change to my flaskapp.py,
server = flask.Flask(__name__)
app = dash.Dash(__name__, server=server, url_base_pathname='/dashapp') #Results in an error
#server.route('/')
def index():
return 'Welcome!'
#server.route('/dash')
def dash_chart():
return flask.redirect('/dashapp')
if __name__ == "__main__":
server.run(debug=True)
I get the following error, AttributeError: 'NoneType' object has no attribute 'traverse'
I think your issue is that you never actually built out the Dash application. I get the same errors you get with your code, but actually building out the Dash app (that is, setting the Layout) seems to fix the issue. Note that the error traceback specifically shows Dash failing to traverse your layout, because there isn't one. Try creating a dash.Layout() for it to parse, so that it has something to serve. An answer to issue #220 on Dash's GitHub mentions this same error and solution.
For a MCVE:
import dash
import dash_html_components as html
import flask
server = flask.Flask(__name__)
app = dash.Dash(__name__, server=server, url_base_pathname='/dashapp')
app.layout = html.Div(children=[
html.H1(children='Dash App')])
#server.route('/')
def index():
return '''
<html>
<div>
<h1>Flask App</h1>
</div>
</html>
'''
if __name__ == '__main__':
server.run(debug=True)
Each page should look the same, except that host:port/ should show the heading "Flask App", while host:port/dashapp should show the heading "Dash App".

web.py no socket could be created error

When I run this helloworld code I get a "No socket could be created" error.
import web
urls = ("/.*", "hello")
app = web.application(urls, globals())
class hello:
def GET(self):
return 'Hello, world!'
app.run()
The same cod works fine if I enclose the call to app.run() inside of an if statement like this
if __name__ == "__main__":
app.run()
My understanding is that it shouldn't make any difference. Anyone have an explanation?
if you run a py file in command line,the default __name__ attribute will be __main__,and your code is executed from top to bottom.You can refer to this question What does if __name__ == "__main__": do?

App Engine regex issues directing URL to script and handlers

I am trying to break my app into separate scripts. Part of this effort meant breaking the api calls into it's own file. However the calls to the api (like http://example.com/api/game/new no longer work).
My app.yaml contains this:
- url: /api.*
script: api.py
which seems to be redirecting properly because this configuration works:
def main():
application = webapp.WSGIApplication([('/.*', TestPage)], debug=True)
util.run_wsgi_app(application)
however this one doesn't:
def main():
application = webapp.WSGIApplication([('/game/new$', CreateGame),
('/game/(d+)$', GameHandler)],
debug=True)
util.run_wsgi_app(application)
The URL patterns you use in the WSGI application have to be the full path - eg, /api/game/.... The App Engine infrastructure uses the regular expressions in app.yaml to route requests, but it does not modify the request path based on them.
My guess is you are trying to pass some arguments to your handler.
Try this. It will give you a hint.
#!/usr/bin/env python
import wsgiref.handlers
from google.appengine.ext import webapp
class MyHandler(webapp.RequestHandler):
def get(self, string=None):
if string:
self.response.out.write("Hello World!! %s" % string)
else:
self.response.out.write("Hello World!! (and no word)")
def main():
app = webapp.WSGIApplication([
(r'/word/(\w+)/?$', MyHandler),
(r'.*', MyHandler),
], debug=True)
wsgiref.handlers.CGIHandler().run(app)
if __name__ == "__main__":
main()
Hope it helps. Cheers.

web.py on Google App Engine

I'm trying to get a web.py application running on GAE. I hoped that sth like the following might work
import web
from google.appengine.ext.webapp.util import run_wsgi_app
[...]
def main():
app = web.application(urls, globals())
run_wsgi_app(app)
But obviously the app object doesn't conform with the run_wsgi_app function's expectations. The error msg says sth like app has no __call__ function, so I tried passing app.run instead, but that didn't work either.
How can I make the call to run_wsgi_app work?
Here is a snippet of StackPrinter, a webpy application that runs on top of Google App Engine.
from google.appengine.ext.webapp.util import run_wsgi_app
import web
...
app = web.application(urls, globals())
def main():
application = app.wsgifunc()
run_wsgi_app(application)
if __name__ == '__main__':
main()
You don't need to import or use run_wsgi_app, web.py has a runcgi method that works perfectly!
if __name__ == '__main__':
app.cgirun()

Calling a python function over the web using AJAX?

I want to send a string to a python function I have written and want to display the return value of that function on a web page. After some initial research, WSGI sounds like the way to go. Preferably, I don't want to use any fancy frameworks. I'm pretty sure some one has done this before. Need some reassurance. Thanks!
You can try Flask, it's a framework, but tiny and 100% WSGI 1.0 compliant.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
Note: Flask sits on top of Werkzeug and may need other libraries like sqlalchemy for DB work or jinja2 for templating.
You can use cgi...
#!/usr/bin/env python
import cgi
def myMethod(some_parameter):
// do stuff
return something
form = cgi.FieldStorage()
my_passed_in_param = form.getvalue("var_passed_in")
my_output = myMethod(my_passed_in_param)
print "Content-Type: text/html\n"
print my_output
This is just a very simple example. Also, your content-type may be json or plain text... just wanted to show an example.
In addition to Flask, bottle is also simple and WSGI compliant:
from bottle import route, run
#route('/hello/:name')
def hello(name):
return 'Hello, %s' % name
run(host='localhost', port=8080)
# --> http://localhost:8080/hello/world

Categories