Flask route for AngularJS with HTML5 URL mode - angularjs

I have an AngularJS app being served via Flask. I am using the HTML5 routing mode and thus need to redirect several URLs to the client app. I'm not sure how to do the wildcard matching needing to do this correctly. Currently I just match multiple levels of path like this:
#app.route('/ui/')
def ui():
return app.send_static_file('index.html')
#app.route('/ui/<path>')
def ui(path):
return app.send_static_file('index.html')
#app.route('/ui/<path>/<path2>')
def ui(path,path2):
return app.send_static_file('index.html')
Obviously I don't like this and would like to just have one route (everything starting with ui/).

The path url converter can do this for you:
#app.route('/ui/<path:p>')
def ui(p):
return app.send_static_file('index.html')

Related

How to access app's routes inside app engine cron job?

So I have the routes defined for my app inside main.py, something like:
app = webapp2.WSGIApplication([
webapp2.Route('/', handler=HomePage, name="home")
])
Inside the cron job I can't seem to access the routes of the app, for example this doesn't work:
self.uri_for('home')
I found somewhere online a snippet that fixes it, but it's ugly to use:
cls.app.router.add(r)
Where r would be an array of routes.
Is there a way to have acces to the app's routes inside an app engine cron job?
Your example is incorrect, it seems to be a cross between simple routes and extended routes.
To be able to use self.uri_for('home') you need to use named routes, i.e. extended routes:
app = webapp2.WSGIApplication([
webapp2.Route(r'/', handler=HomePage, name='home'),
])
With that in place self.uri_for('home') should work, assuming self is a webapp2.RequestHandler instance.
The workaround just looks ugly, but that is pretty much what uri_for does under the hood as well:
def uri_for(self, _name, *args, **kwargs):
"""Returns a URI for a named :class:`Route`.
.. seealso:: :meth:`Router.build`.
"""
return self.app.router.build(self.request, _name, args, kwargs)

Gae, webapp2 url with multiple parameters

I am currently work on a web app using webapp2, that deals with restaurant in several cities. Some of the url would look like
1. www.example.com/newyork
2. www.example.com/newyork/fastfood
3. www.example.com/newyork/fastfood/tacobell
To handle the first url, I used the following
CITY_RE = r'(/(?:[a-zA-Z0-9]+/?)*)'
app = webapp2.WSGIApplication([(CITY_RE, CityHandler)], debug = True)
How would I handle the url with multiple parameters such as 2 and 3.
I have a similar approach to match urls like /<country>/<region>/<city>/<category>e.g. /usa/california/losangeles/restaurants where I use this regex:
app = webapp2.WSGIApplication([('/([^/]+)/?([^/]*)/?([^/]*)', RegionSearch)], config=settings.w2config, debug=True)
The declare the relevant parameters in the handler class.
class RegionSearch(SearchBaseHandler):
"""Handles regional search requests."""
def get(
self,
region=None,
city=None,
category=None,
subcategory='For sale',
PAGESIZE=50, # items on page
limit=60, # number of days
year=2012,
month=1,
day=1,
next_page=None,
):
I think that you could even do it this way
webapp2.Route('/passwdresetcomplete/<city>/<category>/<name>', handler=RegionSearch, name='regionsearch')

Laravel X AngularJS - prefix/trailing slash

As you know Laravel4 omits the trailing slashes from all URLS.
I've Laravel4 X AngularJS SPA (Single Page Application), and simply my current URLs looks like this:
http://localhost/en#/nglink
What I'd like to achieve is to make links looks like this:
http://localhost/en/#/nglink
So as you can see, I need a prefix slash before the AngularJS links (#/nglink), or a trailing slash after Laravel's links (http:// localhost/en). Is there anyway to achieve this using AngularJS? If not how to achieve it without editing Laravel's core files?
Well, it's possible to achieve that though either AngularJS or Laravel or http server side, but it's better & easier to be done through Laravel itself since we can just override the required classes (URLGenerator mainly) without touching core files, and while keeping the code (server agnostic), so it could work with apache/nginx or any other server with trailing slash (that's why I preferred not to work with htaccess).
Update #1
Laravel 5 / AppServiceProvider::register()
$this->app->bindShared('url', function ($app) {
$routes = $app['router']->getRoutes();
$request = $app->rebinding('request', function ($app, $request) {
$app['url']->setRequest($request);
});
// This is your custom overridden "UrlGenerator" class
$urlGenerator = new UrlGenerator($routes, $request);
return $urlGenerator;
});

How to redirect from appspot domain to custom domain?

I found this post from Amir in regards to redirecting request from google.appspot domain to the custom domain. My question is where do you put something like this using Web2py?
**To just add a custom domain, just follow the instructions here: http://code.google.com/appengine/articles/domains.html
And once that works, you can put a check in your code to forward anyone landing on the appspot.com domain to your domain: (example in python)
def get(self):
if self.request.host.endswith('appspot.com'):
return self.redirect('www.jaavuu.com', True)
# ... your code ...**
At the beginning of your first model file, you can do:
if request.env.http_host.endswith('appspot.com'):
redirect(URL(host='www.yourdomain.com', args=request.args, vars=request.vars))
This will preserve the entire original URL, except for replacing yourdomain.appspot.com with www.yourdomain.com. Note, URL() will automatically fill in the current controller and function, but you have to explicitly pass the current request.args and request.vars to make sure they get preserved.
That goes into your request handler.
Using example from web2py documentation:
Example 8
In controller: simple_examples.py
def redirectme():
redirect(URL('hello3'))
You'd want to do something like this:
def some_function():
if request.env.http_host.endswith('appspot.com'):
redirect(URL('www.yourdomain.com'))
With webapp2 here is something like what I did, where BaseHandler is the type of all my handlers:
class BaseHandler(webapp2.RequestHandler):
def __init__(self, request, response):
self.initialize(request, response)
if request.host.endswith('appspot.com'):
query_string = self.request.query_string
redirect_to = 'https://www.example.com' + self.request.path + ("?" + query_string if query_string else "")
self.redirect(redirect_to, permanent=True, abort=True)

Catch-all routing using Tipfy

Using tipfy, how does one express a catch-all route in urls.py if more specific routes do not match?
Tipfy uses Werkzeug-like routing, so there's this (in urls.py):
def get_rules(app):
rules = [
Rule('/<any>', endpoint='any', handler='apps.main.handlers.MainHandler'),
Rule('/', endpoint='main', handler='apps.main.handlers.MainHandler'),
]
This will match most random entry points into the application (app.example.com/foo, app.example.com/%20 etc) but does not cover the app.example.com/foo/bar case which results in a 404.
Alternatively, is there a graceful way to handle 404 in Tipfy that I'm missing?
I think you want:
Rule('/<path:any>', endpoint='any', handler='apps.main.handlers.MainHandler')
The path matcher also matches slashes.
Maybe you could write custom middle ware:
class CustomErrorPageMiddleware(object):
def handle_exception(self, e):
return Response("custom error page")
To enable it add somewhere to tipfy config:
config['tipfy'] = {
'middleware': [
'apps.utils.CustomErrorPageMiddleware',
]
}
It gives you quite a flexibility - you could for example send mail somewhere to inform that there was a problem. This will intercept all exceptions in your application

Resources