Prototyping: Simplest HTTP server with URL routing (to use w/ Backbone.Router)? - backbone.js

We're working on a Backbone.js application and the fact that we can start a HTTP server by typing python -m SimpleHTTPServer is brilliant.
We'd like the ability to route any URL (e.g. localhost:8000/path/to/something) to our index.html so that we can test Backbone.Router with HTML5 pushState.
What is the most painless way to accomplish that? (For the purpose of quick prototyping)

Just use the built in python functionality in BaseHTTPServer
import BaseHTTPServer
class Handler( BaseHTTPServer.BaseHTTPRequestHandler ):
def do_GET( self ):
self.send_response(200)
self.send_header( 'Content-type', 'text/html' )
self.end_headers()
self.wfile.write( open('index.html').read() )
httpd = BaseHTTPServer.HTTPServer( ('127.0.0.1', 8000), Handler )
httpd.serve_forever()

Download and install CherryPy
Create the following python script (call it always_index.py or something like that) and also replace 'c:\index.html' with the path of your actual file that you want to use
import cherrypy
class Root:
def __init__(self, content):
self.content = content
def default(self, *args):
return self.content
default.exposed = True
cherrypy.quickstart(Root(open('c:\index.html', 'r').read()))
Run python <path\to\always_index.py>
Point your browser at http://localhost:8080 and no matter what url you request, you always get the same content.

Related

Flask webserver with React client and RestFull API

How are you?
I'm trying to maintain two services on the same flask web server: A React client (available in "/") and a RestFull API (available in "/api/").
However, all routes are directed to the client and I cannot register the Blueprint to "/api".
#app.route('/', defaults={'path': ""})
#app.route('/<path:path>')
def client_route(path):
return 'Client'
app.register_blueprint(routes, url_prefix="/api")
""" Registro de rotas da aplicação """
printscreen code
I need routes starting with "/api" to call the API routes, while all other routes (*) call Client React.
Can anybody help me??
main_view.py
bp = Blueprint('main', name, url_prefix='/api')
app.py
app.register_blueprint(main_view.bp)
When setting the blue print, enter '/api' instead of 'prefix = /' section. oh You've already set it up like that, but in my case I write above .
I hope this helps.
You must enter api not \api.
Here is a link on how blueprints work: https://realpython.com/flask-blueprint/
I found the solution!
You just need to swap the order of the register, like that:
app.register_blueprint(routes, url_prefix="/api")
""" Registro de rotas da aplicação """
#app.route('/', defaults={'path': ""})
#app.route('/<path:path>')
def client_route(path):
if path != "" and os.path.exists(app.static_folder + '/' + path):
return send_from_directory(app.static_folder, path)
else:
return send_from_directory(app.static_folder, 'index.html')
(*) And you may use this React code to serve the webapp correctly.
Thaks!!

How to do a Post/Redirect/Get (PRG) in FastAPI?

I am trying to redirect from POST to GET. How to achieve this in FastAPI?
What did you try?
I have tried below with HTTP_302_FOUND, HTTP_303_SEE_OTHER as suggested from Issue#863#FastAPI: But Nothing Works!
It always shows INFO: "GET / HTTP/1.1" 405 Method Not Allowed
from fastapi import FastAPI
from starlette.responses import RedirectResponse
import os
from starlette.status import HTTP_302_FOUND,HTTP_303_SEE_OTHER
app = FastAPI()
#app.post("/")
async def login():
# HTTP_302_FOUND,HTTP_303_SEE_OTHER : None is working:(
return RedirectResponse(url="/ressource/1",status_code=HTTP_303_SEE_OTHER)
#app.get("/ressource/{r_id}")
async def get_ressource(r_id:str):
return {"r_id": r_id}
# tes is the filename(tes.py) and app is the FastAPI instance
if __name__ == '__main__':
os.system("uvicorn tes:app --host 0.0.0.0 --port 80")
You can also see this issue here at FastAPI BUGS Issues
I also ran into this and it was quite unexpected. I guess the RedirectResponse carries over the HTTP POST verb rather than becoming an HTTP GET. The issue covering this over on the FastAPI GitHub repo had a good fix:
POST endpoint
import starlette.status as status
#router.post('/account/register')
async def register_post():
# Implementation details ...
return fastapi.responses.RedirectResponse(
'/account',
status_code=status.HTTP_302_FOUND)
Basic redirect GET endpoint
#router.get('/account')
async def account():
# Implementation details ...
The important and non-obvious aspect here is setting status_code=status.HTTP_302_FOUND.
For more info on the 302 status code, check out https://httpstatuses.com/302 Specifically:
Note: For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request. If this behavior is undesired, the 307 Temporary Redirect status code can be used instead.
In this case, that verb change is exactly what we want.

X-Appengine-Inbound-Appid header not set

I have two AppEngine modules, a default module running Python and "java" module running Java. I'm accessing the Java module from the default module using urlfetch. According to the AppEngine docs (cloud.google.com/appengine/docs/java/appidentity), I can verify in the Java module that the request originates from a module in the same app by checking the X-Appengine-Inbound-Appid header.
However, this header is not being set (in a production deployment). I use urlfetch in the Python module as follows:
hostname = modules.get_hostname(module="java")
hostname = hostname.replace('.', '-dot-', 2)
url = "http://%s/%s" % (hostname, "_ah/api/...")
result = urlfetch.fetch(url=url, follow_redirects=False, method=urlfetch.GET)
Note that I'm using the notation:
<version>-dot-<module>-dot-<app>.appspot.com
rather than the notation:
<version>.<module>.<app>.appspot.com
which for some reason results in a 404 response.
In the Java module I'm running a servlet filter which looks at all the request headers as follows:
Enumeration<String> headerNames = httpRequest.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = httpRequest.getHeader(headerName);
mLog.info("Header: " + headerName + " = " + headerValue);
}
AppEngine does set some headers, e.g. X-AppEngine-Country. But the X-Appengine-Inbound-Appid header is not set.
Why am I'm not seeing the documented behaviour? Any suggestions would be much appreciated.
Have a look at what I've been answered on Google groups, which led to an issue opened on the public issue tracker.
As suggested in the answer I received you can follow, for any update, the issue over there.

flask: error_handler for blueprints

Can error_handler be set for a blueprint?
#blueprint.errorhandler(404)
def page_not_found(error):
return 'This page does not exist', 404
edit:
https://github.com/mitsuhiko/flask/blob/18413ed1bf08261acf6d40f8ba65a98ae586bb29/flask/blueprints.py
you can specify an app wide and a blueprint local error_handler
You can use Blueprint.app_errorhandler method like this:
bp = Blueprint('errors', __name__)
#bp.app_errorhandler(404)
def handle_404(err):
return render_template('404.html'), 404
#bp.app_errorhandler(500)
def handle_500(err):
return render_template('500.html'), 500
errorhandler is a method inherited from Flask, not Blueprint.
If you are using Blueprint, the equivalent is app_errorhandler.
The documentation suggests the following approach:
def app_errorhandler(self, code):
"""Like :meth:`Flask.errorhandler` but for a blueprint. This
handler is used for all requests, even if outside of the blueprint.
"""
Therefore, this should work:
from flask import Blueprint, render_template
USER = Blueprint('user', __name__)
#USER.app_errorhandler(404)
def page_not_found(e):
""" Return error 404 """
return render_template('404.html'), 404
On the other hand, while the approach below did not raise any error for me, it didn't work:
from flask import Blueprint, render_template
USER = Blueprint('user', __name__)
#USER.errorhandler(404)
def page_not_found(e):
""" Return error 404 """
return render_template('404.html'), 404
add error handling at application level using the request proxy object:
from flask import request,jsonify
#app.errorhandler(404)
#app.errorhandler(405)
def _handle_api_error(ex):
if request.path.startswith('/api/'):
return jsonify(ex)
else:
return ex
flask Documentation
I too couldn't get the top rated answer to work, but here's a workaround.
You can use a catch-all at the end of your Blueprint, not sure how robust/recommended it is, but it does work. You could also add different error messages for different methods too.
#blueprint.route('/<path:path>')
def page_not_found(path):
return "Custom failure message"
Surprised others didn't mention miguelgrinberg's excellent tutorial.
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-error-handling
I found the sentry framework for error handling (links below). Seems overly complex. not sure of the threshold where it becomes useful.
https://flask.palletsprojects.com/en/1.1.x/errorhandling/
https://docs.sentry.io/platforms/python/guides/flask/
I combined previous excellent answers with the official docs from Flask, section 'Returning API Errors as JSON', in order to provide a more general approach.
Here is a working PoC that you can copy and paste on your registered blueprint API route handler (e.g. app/api/routes.py):
#blueprint.app_errorhandler(HTTPException)
def handle_exception(e):
"""Return JSON instead of HTML for HTTP errors."""
# start with the correct headers and status code from the error
response = e.get_response()
# replace the body with JSON
response.data = json.dumps({
"code": e.code,
"name": e.name,
"description": e.description,
})
response.content_type = "application/json"
return response
Flask doesnt support blueprint level error handlers for 404 and 500 errors. A BluePrint is a leaky abstraction. Its better to use a new WSGI App for this, if you need separate error handlers, this makes more sense.
Also i would recommend not to use flask, it uses globals all over the places, which makes your code difficult to manage if it grows bigger.

Catch All Script in App Engine Python (APP.YAML) does not work in Static Files

I have tried everything but it seems that you cannot get a catch all url...
- url: /.*
script: not_found.py
...to work on urls that are based on static directory paths. eg. I can type in www.foobar.com/asdas/asd/asd/asd/ad/sa/das/d and I can get a nice custom 404 page. But if I alter a static path url like www.foobar.com/mydir/mydir/mypage.html, I just get the horrible generic 404....
Error: Not Found
The requested URL /mydir/mydir/mypage.html was not found on this server.
... I would like to alter whatever catches the url in directory paths and writes the 404. This appears the only way to get a consistent custom 404 page in GAE Python.
Can anyone help? I have written my website from scratch and have a very limited knowledge of Python. Achieving a consistent custom 404 is the only thing I cannot seem to overcome.
EDIT/ADD : OK I've added the kind suggestion of #Lipis , and gone through getting started which which thankfully has given me a much better understanding of classes (I sadly can't vote it up yet). But! I am using a .py script found on the net and I think the NotFound class is interfering with the class that gives my index page, because now my index page is the 404 page specified by the Jinja! I have very little understanding of MainHandler so I may have to give up for now.
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
import jinja2
class MainHandler(webapp.RequestHandler):
def get (self, q):
if q is None:
q = 'index.html'
path = os.path.join (os.path.dirname (__file__), q)
self.response.headers ['Content-Type'] = 'text/html'
self.response.out.write (template.render (path, {}))
class NotFound(webapp.RequestHandler):
def post(self):
# you need to create the not_found.html file
# check Using Templates from Getting Started for more
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
template = jinja_environment.get_template('404.html')
self.response.out.write(template.render(template_values))
def main ():
application = webapp.WSGIApplication ([('/(.*html)?', MainHandler),('/.*', NotFound)],
debug=True)
util.run_wsgi_app (application)
if __name__ == '__main__':
main ()
For better understanding I'll make some modifications on the Getting Started example which I assume that you have done it and you made some experiments with it.
It's not a good idea to have the static file for all the not found pages in the app.yaml since most likely you would like to show something more dynamic and usually the - url: /.* should be handled within your app.
In this example we are going to add a new RequestHandler for all your not found pages
import jinja2
import os
# more imports
jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
class MainPage(webapp2.RequestHandler):
def get(self):
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
class NotFound(webapp.RequestHandler):
def get(self):
# you need to create the not_found.html file
# check Using Templates from Getting Started for more
template = jinja_environment.get_template('not_found.html')
self.response.out.write(template.render(template_values))
application = webapp.WSGIApplication(
[('/', MainPage),
('/.*', NotFound)], # <-- This line is important
debug=True)
But in order to make the jinja2 templates work, follow carefully the modifications that you need to do in Using Templates section from the Getting Started.
The order in the URL mapping is very important so this catch all regular expression (/.*) should be always the last one, because otherwise all the other rules will be skipped.
If you want to catch all URLs, you will have to modify your main request handler in your file "not_found.py" by adding '/.*'.
For example, you can set the file "not_found.py" to:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write("Hello, MAIN!")
application = webapp.WSGIApplication(
[('/.*', MainHandler)], # <--- Add '/.*' here
debug=True)
def main():
run_wsgi_app(application)
If you navigate to www.foobar.com/asd/ad/sa/das/d or any other URL, you will see the message "Hello, MAIN!.
Hope it helps. Ask question if needed

Resources