Flask url_for on external URLs - python

I have been researching this for quite a while and it seems that I cannot get my head around it. I have different ideas but all of them looks like they are not the right one to solve this problem.
I have an application in flask that does different things like for example:
loading an image (user profile image)
calling APIs (to perform specific tasks, like for example adding a comment to a forum post)
etc.
The way I am doing all of this is by using url_for in this way:
client_info = requests.post(url_for('api.read_comments', _external=True),
json={'client_name': client}).json()
So my application is at "https://www.myapp.com/comments" - The "url_for()" in my code will basically generate this url: "https://www.myapp.com/api/read_comments".
All comments are then retrieved by my API code.
This works just fine, but what I would like to do is to have the Frontend on "https://www.myapp.com/" but the Backend on "https://backend.myapp.com".
So my question is, how can I make my url_for() as dynamic as possible and able to access content on other subdomains/servers that I own?
Any thoughts? Or additional methods/functions that I should be using?
For example all comments will be located at "comments.myapp.com", all my profile details are on "profiles.myapp.com", etc. This is just a general idea on how the system can be setup. Any thoughts?
Thanks a lot and I look forward to hearing from you.

Related

Flask and obtaining a full absolute path to a route

I'm looking to integrate some API's through a web application interface, to achieve this I need to identify the absolute path for a specific route. As I dont want to hard code any urls I'd like to do this dynamically in the flask app.
I thought that should be simple enough and tried a couple of things:
abs_url = url_for('home')
This didn't work of course as it just returned the route. I since learnt that url_for requires the function name. It then returns the route ('/home' for example).
I then tried:
abs_url = redirect(url_for('home'))
This gave me a redirect object, I was hoping path may be a variable I could call, however that doesnt seem to be the case.
Google has not been my friend today and hasn't given me anything to go on and advice would be appreciated.
The more I think about this the more I think the simplest option would be to capture the application address as part of the configuration.
To resolve this I have captured the application address as part of the initial info gathering form.

Django figure out which template rendered the view you are seeing

So, I've recently inherited a large code base that is fairly obfuscated. When I navigate a page on my local machine is there any way to determine which template/view is actually being called to create the view that I'm seeing at that moment?
I would like to get a better idea of where certain parts of the page are actually coming from, but the project is so large and disorganized that going through present templates is simply not feasible.
Is there any nice way to get around this? Worth mentioning that the defined urls all seem to be poorly written, obfuscated regex, (not to mention incredibly long) so direct examination of the urls file is not extremely feasible.
When I try to run resolve on the url of the page I'm trying to view I get a 404, and I'm not really sure where to progress from there, since the page clearly works.
Any help would be greatly appreciated.
Personnaly I use this : https://github.com/django-debug-toolbar/django-debug-toolbar
The Django Debug Toolbar is a configurable set of panels that display
various debug information about the current request/response and when
clicked, display more details about the panel's content.
Currently, the following panels have been written and are working:
Django version
Request timer
A list of settings in settings.py
Common HTTP headers
GET/POST/cookie/session variable display
Templates and context used, and their template paths
SQL queries including time to execute and links to EXPLAIN each query
List of signals, their args and receivers
Logging output via Python's built-in logging, or via the logbook module
There is also one Django management command currently:
debugsqlshell: Outputs the SQL that gets executed as you work in the Python interactive shell. (See example below)
If you have ideas for other panels please let us know.
Note: The Debug Toolbar only works on Django 1.3 and newer.
0 code to add, only a few minor changes to settings.py
You will get what you want and even more.

Huge Django project

I have a new job and a huge django project (15 apps, more than 30 loc). It's pretty hard to understand it's architecture from scratch. Are there any techniques to simplify my work in the beginning? sometimes it's even hard to understand where to find a form or a view that I need... thnx in advance.
When I come to this kind of problem I open up a notebook and answer the following:
1. Infrastructure
Server configuration, OS etc
Check out the database type (mysql, postgres, nosql)
External APIS (e.g Facebook Connect)
2. Backend
Write a simple description
Write its input/output from user (try to be thorough; which fields are required and which aren't)
Write its FK and its relation to any other apps (and why)
List down each plugin the app is using. And for what purpose. For example in rails I'd write: 'gem will_paginate - To display guestbook app results on several pages'
3. Frontend
Check out the JS framework
Check the main stylesheet files (for the template)
The main html/haml (etc) files for creating a new template based page.
When you are done doing that. I think you are much more prepared and able go deeper developing/debugging the app. Good luck.
Use this http://packages.python.org/django-extensions/graph_models.html
to generate the Relationship diagrams from the models so that you can visually see how the models are related to each other. This will give you nice idea about the app
1) Try to install the site from scratch. You will find what external apps are needed for the site to run.
2) Reverse engineer. Browse through the site and try to find out what you have to do to change something to that page. Start with the url, look up in urls.py, read the view, check the model. Are there any hints to other processes?
3) Try to write down everything you don't understand, and document the answers for future reference.
I would clone the project so you can mess up endlessly.
Then I would start to reduce the code. "What happens if if just remove this function here?
Also get django debug toolbar:
https://github.com/django-debug-toolbar/django-debug-toolbar
A good terminal debugger is also golden, there are many out there, here is an example:
https://github.com/tomchristie/django-pdb
This allow you to halt the code and even inject and mutate parameters in runtime. Just like GDB in C.
If you use FireFox you can install FireBug on it and when you for example submit ajax form you can see at which url send you request after what you can easily find controller which work with this form data. At chrome this utility embedded by default and call by F12 key.

How the url internationalization should be made?

I have a question regarding the internationalization of a website's URL addresses.
The question is how to make it properly?
What I would like to do is something like this.
Assume you have an URL in your address bar
www.mydomain.com/en/book
then if you type www.mydomain.com/de/book you will be redirected to a german version of a site so the url will change to www.mydomain.com/de/buch and so on.
Idea:
I thought about making a table that would be used as a dictionary between different languages. For the website content I would still use i18n, but I think that for urls it cannot be applied.
The implementation:
I thought about modifying routing.py in a way that before any connection is invoked I would recognize in the URL a language that user wants, and store it in a session variable for later use with i18n. Then I would redirect user to a correct url for this lanugage and invoke a poper controller/action.
Any ideas, suggestions or recomendations are welcome.
Edit (2011-04-04 18:35):
I have just reminded myself that I have already encountered a similar problem on Opera Blog;
there is a problem on StackOverflow: Pylons application Internationalization, but it deals solely on site internationalization, no problem with URLs included;
WZeberaFFS has pointed our a small issue that may arise if no reference or previous language settings are taken into account;
Additional question: What should be stored in database, to make it work fast? I have my own idea, but I will give it a try later on.
I believe your implementation will work as log as you don't have the same name of to different pages like if you have a page called www.mydomain.com/en/music and if music in German is book, then the problem will be that if you want to go to www.mydomain.com/fr/music then you don't know if you are coming form /de/ or /en/. But this is only a problem if you have colliding names on different pages cross languish it will still work if you have the same name for a word in 2 different languish you wont really know where they cam form but you will know where they are heading.
If you have that problem then you have to save a session or hope that the client sends a referral.
I have no idea how it could be done in Python, but usually people do such things through some kind of URL Re-writer or URL filter - something that will consume your URL and re-direct to proper page setting Locale at the same time.

What to do after starting simple_server?

For some quick background, I'm an XHTML/CSS guy with some basic PHP knowledge. I'm trying to dip my feet into the Python pool, and so far understand how to start simple_server and access a simple Hello World return in the same .py file. This is the extent of what I understand though, heh.
How do I integrate the simple_server and your basic XHTML/CSS files? I want to start the server and automagically call, for instance, index.py (does it need to be .py?). Obviously within the index file I would have my markup and stylesheet and I would operate it like a normal site at that point.
My eventual goal is to get a basic message board going (post, edit, delete, user sessions). I realize I'll need access to a database, and I know my way around MySQL enough to not have to worry about those portions.
Thanks for the help.
EDIT: Allow me to clarify my goal, as I have been told Python does a LOT more than PHP. My goal is to begin building simple web applications into my pre-existing static XHTML pages. Obviously with PHP, you simply make sure its installed on your server and you start writing the code. I'd like to know how different Python is in that sense, and what I have to do to, say, write a basic message board in Python.
The other answers give good recommendations for what you probably want to do towards your "eventual goal", but, if you first want to persist with wsgiref.simple_server for an instructive while, you can do that too. WSGI is the crucial "glue" between web servers (not just the simple one in wsgiref of course -- real ones, too, such as Apache or Nginx [both with respective modules called mod_wsgi] as well as, for example, Google App Engine -- that one offers WSGI, too, as its fundamental API) and web applications (and frameworks that make it easier to write such applications).
Everybody's recommending various frameworks to you, but understanding WSGI can't hurt (since it will underlie whatever framework you eventually choose). And for the purpose of such understanding wsgiref.simple_server will serve you for a while longer, if you wish.
Essentially, what you want to do is write a WSGI app -- a function or class that takes two parameters (an "enviroment" dictionary, and a "start response" callable that it must call back with status and headers before returning the response's body). Your "WSGI app" can open your index.py or whatever else it wants to prep the status, headers and body it returns.
There's much more to WSGI (the middleware concept is particularly powerful), though of course you don't have to understand it very deeply -- only as deeply as you care to! See wsgi.org for tutorials &c. Gardner's two-part article, I think, is especially interesting.
Once (and if that's your choice) you understand WSGI, you can better decide whether you want it all hidden in a higher level framework such as Django (so you can focus on application-level issues instead) or use a very light and modular toolbox of WSGI utilities such as Werkzeug -- or anything in-between!-)
I would recommend Django.
"Obviously with PHP, you simply make sure its installed on your server and you start writing the code."
Not true with Python. Python is just a language, not an Apache plug-in like PHP.
Generally, you can use something like mod_wsgi to create a Python plug-in for Apache. What you find is that web page processing involves a lot of steps, none of which are part of the Python language.
You must use either extension libraries or a framework to process web requests in Python. [At this point, some PHP folks ask why Python is so popular. And the reason is because you have choices of which library or framework to use.]
PHP parses the request and allows you to embed code in the resulting page.
Python frameworks -- generally -- do not work this way. Most Python frameworks break the operation down into several steps.
Parsing the URL and locating an appropriate piece of code.
Running the code to get a result data objects.
Interpolating the resulting data objects into HTML templates.
"My goal is to begin building simple web applications into my pre-existing static XHTML pages."
Let's look at how you'd do this in Django.
Create a Django project.
Create a Django app.
Transform your XTHML pages into Django templates. Pull out the dynamic content and put in {{ somevariable }} markers. Depending on what the dynamic content is, this can be simple or rather complex.
Define URL to View function mappings in your urls.py file.
Define view functions in your views.py file. These view functions create the dynamic content that goes in the template, and which template to render.
At that point, you should be able to start the server, start a browser, pick a URL and see your template rendered.
"write a basic message board in Python."
Let's look at how you'd do this in Django.
Create a Django project.
Create a Django app.
Define your data model in models.py
Write unit tests in tests.py. Test your model's methods to be sure they all work properly.
Play with the built-in admin pages.
Create Django templates.
Define URL to View function mappings in your urls.py file.
Define view functions in your views.py file. These view functions create the dynamic content that goes in the template, and which template to render.
Take a look at CherryPy. It's a nice http framework.
It depends on what you want to achieve,
a) do you want to just write a web application without worrying too much abt what goes in the background, how request are being handled, or templates being rendered than go for a goo webframework, there are many choices simple http server is NOT one of them. e.g. use django, turbogears, webpy, cheerpy, pylons etc etc
see http://wiki.python.org/moin/WebFrameworks for full list
b) if you want to develope a simple web framework from start so that you understand internals and improve you knowledge of python, then I will suggest use simple http server
see
how can you create a URL scheme so that URLs are dispatched to correct python function,
see how can you render a html
template e.g. containing place
holder variables $title etc which
you can convert to string using
string.Template
b) would be difficult but interesting exercise to do, a) will get you started and you may be writing web apps in couple of days

Categories