I have a fairly large Flask application and I have encountered a need to create view functions in a separate python module. Right now I have all of my view functions in one module where I create my Flask app object, all my view functions, and run the Flask dev server. All of these views so far are urls that users will actually see when using the application so I am okay with keeping these in this existing module. However, I need to have an API where another application will be posting JSON to specific urls. I would like to keep these API handlers (views) separate from the other views.
I have already read the documentation here http://flask.pocoo.org/docs/0.10/patterns/packages/. The way I see it I have two options. I can put my application in a package and create the Flask app in the __init_.py, then import views from each file there as well, with a module to run the app next to the package like it is shown in the docs, or I can create a blueprint for my API handlers and register the blueprint in my existing module.
I am not sure what is the best way to go about this. I am leaning towards blueprints but I need feedback on what other people have done in this situation.
This question is not generally a good question for Stack Overflow, since it appears you're asking for an opinion and your question is vague. You should post code that you've already tried and have a more specific question.
Since you're new, I'll answer as best I can, with the very limited information you posted.
I highly recommend using Blueprints for your situation. It will make it a lot easier in the future to manage the application if it's broken up into modules that are glued together with blueprints. Then you would have a small __ init__.py script, that primarily registers the blueprints.
Related
I apologize if this seems like a stupid question but I'm still very much a novice Python/Django programmer. Is it normal to create Python objects in a Django application that aren't models that will be saved in the database?
I'm creating what's become a fairly large Django application and, to me, my code is really starting to "smell". What I mean is that my views are becoming very large because I'm taking a procedural rather than object-oriented approach. My intuition tells me that my code might be simpler, easier to test, and more robust in the long run if I were using more objects with their own attributes and behaviors rather than passing information from one function to the next in my views.
What's hanging me up is that these aren't objects I want to save in my database so I don't quite know if I should be using them and, if I should, where I'd put them. Is the approach I'm proposing typical in a Django application? If so, where would I store those objects with respect to the Django model/view/template structure? Also, are there any popular Django modules or libraries that do what I'm describing that I should study?
Thanks in advance for your response.
You can store your objects anywhere. There could be helper functions in your views file or models file or wherever. I prefer to put miscellaneous functions in a utils.py file but that is not a convention, just something I end up doing. I end up putting most of miscellaneous helper functions and base classes in a common app, and more specifically a common.utils file.
In one project I have lots of apps, and each app has an api client. The base class for the client resides in an app called common. Then each app then has their specific client in client.py file
project
common
client
app1
client
app2
client
Then in app1 client
from project.common.client import BaseClient
class ConcreteApp1Client(BaseClient):
pass
Then in my views or management commands or models or wherever the concrete client can be imported and used as normal. from project.app1.client import ConcreteApp1Client
Django also has class-based views if you feel certain variables could best be encapsulated in a class.
https://docs.djangoproject.com/en/dev/topics/class-based-views/
I have read the official Flask documentation on Blueprints and even one or two blog posts on using them.
I've even used them in my web app, but I don't completely understand what they are or how they fit into my app as a whole. How is it similar to an instance of my app but not quite? The documentation is comprehensive but I seek a layman explanation or an enlightening analogy to spark it for me. I was sufficiently perplexed when a colleague asked me to explain a Flask blueprint to them that I elected to ask here.
A blueprint is a template for generating a "section" of a web application. You can think of it as a mold:
You can take the blueprint and apply it to your application in several places. Each time you apply it the blueprint will create a new version of its structure in the plaster of your application.
# An example
from flask import Blueprint
tree_mold = Blueprint("mold", __name__)
#tree_mold.route("/leaves")
def leaves():
return "This tree has leaves"
#tree_mold.route("/roots")
def roots():
return "And roots as well"
#tree_mold.route("/rings")
#tree_mold.route("/rings/<int:year>")
def rings(year=None):
return "Looking at the rings for {year}".format(year=year)
This is a simple mold for working with trees - it says that any application that deals with trees should provide access to its leaves, its roots, and its rings (by year). By itself, it is a hollow shell - it cannot route, it cannot respond, until it is impressed upon an application:
from tree_workshop import tree_mold
app.register_blueprint(tree_mold, url_prefix="/oak")
app.register_blueprint(tree_mold, url_prefix="/fir")
app.register_blueprint(tree_mold, url_prefix="/ash")
Once it is created it may be "impressed" on the application by using the register_blueprint function - this "impresses" the mold of the blueprint on the application at the locations specified by url_prefix.
As pointed out in a comment by #Devasish, this article provides a good answer:
http://exploreflask.com/en/latest/blueprints.html
Quoting from the article:
An example of this would be Facebook. If Facebook used Flask, it might
have blueprints for the static pages (i.e. signed-out home, register,
about, etc.), the dashboard (i.e. the news feed), profiles
(/robert/about and /robert/photos), settings (/settings/security and
/settings/privacy) and many more. These components all share a general
layout and styles, but each has its own layout as well
This is a very good interpretation, especially the part "if Facebook used Flask". It gives us a concrete situation to visualize how Blueprint actually works.
For bigger projects, all your code shouldn't be in the same file.
Instead you can segment or split bigger codes into separate files, mostly based on functionality. Like bricks forming a wall.
A simple Flask app
app = Flask(__name__)
A blueprinted Flask app
import from_any_module.part_1
import from_other_module.part_2
app = Flask(__name__)
app.register_blueprint(part_1)
app.register_blueprint(part_2)
A blueprint in the above app
from flask import Blueprint
part_1 = Blueprint(part_1)
#part_1.route('/url')
def function()
return view
I too just stumbled up this myself and was confused after reading a few of the documentation sources. At first I thought it was like C#/Java OOP Interface Implementation style where you define some stuff but dont have to worry about it implementation details til later. However, I stumbled up this page which puts it in very very laymens (and quite hilarious present-day events) terms. https://hackersandslackers.com/flask-blueprints/
Essentially one benefit that is mentioned in the link and provides me a clear idea of it's real world usage is that I can effectively logically organize/divide the app into several parts that only need to be concerned with it's own affairs. So it provides some designed encapsulation.
Edit: I'm currently using it to segment out my webapps code. It was good decision too because I found the lead designer wants to make the frontend in Vue.js. Which I havent used yet but looking at it's project files would look far more messy and probably provide many naming collision prone instances due to files with similar names
A Flask blueprint helps you to create reusable instances of your application. It does so by organizing your project in modules. Those modules are then registered the main application. They help in creating an application factory.
This question has been troubling me for some days now and I've tried asking in many places for advice, but it seems that nobody can answer it clearly or even provide a reference to an answer.
I've also tried searching for tutorials, but I just cannot find any type of tutorial that explains how you would use a reusable third-party django app (most tutorials explain how to write them, none explain how to use them).
Also, I've taken a look here:
How to re-use a reusable app in Django - it doesn't explain how to actually use it IN a project itself
and here:
How to bind multiple reusable Django apps together? - the answer by aquaplanet kind of makes sense, but I thought I would ask this question to solve the mental block I am facing in trying to understand this.
In order to best explain this, let me do so by example (note, it is not something I am actually building).
I am creating a project that acts like Reddit. I will have users, links and voting/points. Based on this crude example, I will want to reuse 3 (arbitrary) third-party apps: user, voting/points and links.
I decide to use each of them as any other python package (meaning that they will be treated as a package and none of their code should be touched) [would this method actually work? Or do you have to be able to edit third-party apps to build a project??)
With these apps now within my project, I will use a main app to handle all the template stuff (meaning everything I see on the frontend will be in a single app).
I will then either use that same main app for custom logic (in views.py) or I will break up that logic among different apps (but will still use a single frontend-only app).
From the 3 paragraphs above, is this structure applicable (or can it work) ?
Now lets say that this structure is applicable and I am using a single main app for the frontend and custom logic.
What would I write in models.py? How would I integrate things from the 3 reusable apps into the main models.py file?
How would I reference the reusable apps in views.py? Lets take the example of contrib.auth
With this built-in app, for logging out I would write:
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
#login_required
def user_logout(request):
logout(request)
return redirect('/home/')
Although the above code is simple, is that basically how things would be done with any reusable app?
My question is very long, but I think that this reusable app issue is something a lot of developers aren't quite clear about themselves and maybe this answer will help a lot of others who have heard about the promises of reusable apps, but fail to understand how to actually use them.
TL;DR:
Nope & it depends...
Some (Very) Common Reusable Apps
django.contrib.admin
django.contrib.auth
django.contrib.staticfiles
... those are all reusable Django apps, that happen to be shipped with Django (most of them were not, at some point in time)
Ok, some other reusable apps that don't ship with Django:
django-rest-framework
django-registration
South
Those are all truly reusable apps, and nothing less. There are very many more apps like that.
How do they do it?
To me your question looks more like "how do I build reusable apps", then "how to use them". Actually using them is very different from app to app, because they do very different things. There is only one rule: RTFM No way around that either.
Often, they rely on one or more of the following:
additional value(s) in settings.py
addition (usually one include statement) to urls.py
subclassing and/or mixins for Models, Forms, Fields, Views etc.
template tags and/or filters
management commands
...
Those are all powerful ways though which your app can provide functionality to other apps. There is no recipe (AFAIK) to make a reusable app, because there are so many different scenarios to consider. It all depends on what exactly your app should do.
Reusable apps provide functionalities
I'd argue that it's important to not think of reusable apps as "working together" with other app, but instead recognize that that they "provide functionality." The details of the functionality provided should dictate the way the target developer is supposed to use your library.
Not everything should be reusable
Obviously enough, even though many apps can "in principle" be reusable, it often makes little sense to do so, because it is way faster to clump things together (and make them just "work together").
I'm not sure why you think you need a main app for the "frontend" stuff. The point of a reusable app is that it takes care of everything, you just add (usually) a single URL to include the urls.py of the app, plus your own templates and styling as required.
And you certainly don't need to wrap the app's views in your own views, unless you specifically want to override some functionality.
I don't understand at all your question about models. There's no such thing as a "main" models file, and using a reusable app's models is just the same as using models from any of your own apps.
Normally you would not edit a third-party app, that would make it very hard to integrate updates. Just install the app in your virtualenv (you are using virtualenv, of course!) with pip, which will put it in the lib directory, and you can reference it just like any other app. Make sure you add it to INSTALLED_APPS.
I want to switch from Rails to Django, to broaden my mind, and a question has bobbed up in my mind.
My Rails app is quite a mess, since my hobby-based development approach is a patch-and-glue one. I have seen very early that Django divied between a project and an app. According to their site, a project is made of many apps, and one app can be used for many projects.
This intrigued me, since that would made the lines between my site's areas clearer. I tried to find some more examples and information on that, but I couldn't answer my question, which is:
How big/small is such an app? Are they able/supposed to interact closely?
It is, for example smart to have one app to deal with user's profiles, and another app to deal with blog-posts and comments, from those users? (In my site, a user can have several blogs, with different profiles). Or are they meant to be used otherwise?
A django App is a fancy name for a python package. Really, that's it. The only thing that would distinguish a django app from other python packages is that it makes sense for it to appear in the INSTALLED_APPS list in settings.py, because it contains things like templates, models, or other features that can be auto-discovered by other django features.
A good django app will do just one thing, do it well, and not be tightly coupled to any other app that might use it. A wide variety of apps are provided with django in the contrib namespace that follow this convention.
In your example, a good way to devise apps is to have one for user profiles (or use one of the many existing profile apps), one app for blog posts (or one of the many that already do this), one app for comments, separate from blog posts (again, you can use an existing app for this), and finally, a very tiny app that ties the three together, since they don't and shouldn't depend on each other directly.
The purpose of using app's is to make them reusable. Django likes DRY principle DRY stands for DO NOT repeat yourself
An app should be as small as it can, and loosely coupled. So, for an app should not need another app to work properly.
Django recommends writing an app for each table (well, not always, but as soon as you want to grow your app, you will definitely need to divide tables to pair apps. Or else you will have hard time for maintaining your code.)
You can, for example, create an app for users, an app for sales, an app for comments, an app for articles. It will be easier to maintain your code and if you have done it right, you can use the app in other project with a little (if any) modification in the app.
Project's are, compilation of app's. Users app, articles app, comments app can come together an make a project, or in other words, a website.
If you want to learn django, I suggest you to check out:
http://www.djangobook.com/
http://docs.djangoproject.com/
One word of advice, do not, in any case, copy/paste. Not only your code has great chance to fail, but you will not know what the code is doing. If you are going to use someone elses code in your project, at least type them, this will make you understand what the code is doing, or at least, it will give an idea.
Writing your own code is always better for maintance, but this does not mean that you should reinvent the world, you can use libraries, look at their documentation to use it properly.
Documentations, tutorials are you best friend.
Good luck.
A project is basically a place where your project lives...in your project you setup your url's, project settings, etc.
An app defines its own data models and views to be used within a project. You can move these between projects if you like.
I highly recommend running through the tutorials from the Django site as they will show you what a project and app are, how to manage both, how to use the admin panel, how to make the app usable in multiple projects, etc.
A portal = A django project
A ads system, gallery photos, catalog of products = Apps
I just wanted to try to build a project with django. Therefore I have a (basic) question on how to manage such a project. Since I cannot find any guidelines or so on how to split a project into applications.
Let's take a kind of SO as an example. Which applications would you use?
I'd say there should be the applications "users" and "questions". But what if there was a topic system with static articles, too. Maybe they also could receive votes.
How to build the apps structure then? One app for "questions", "votes" and "topics" or just one app "content"?
I have no idea what to do. Maybe it's because I know not very much about Django yet, but I'm interested either...
There aren't hard-and-fast rules, but I would say it's better to err on the side of more specialized applications. Ideally an application should handle just one functional concern: i.e. "tagging" or "commenting" or "auth/auth" or "posts." This type of design will also help you reuse available open source applications instead of reinventing the wheel (i.e. Django comes with auth and comments apps, django-tagging or django-taggable can almost certainly do what you need, etc).
Generic foreign keys can help you decouple applications such as tagging or commenting that might be applied to models from several other applications.
You should try and separate the project in as much applications as possible. For most projects an application will not contain more than 5 models. For example a project like SO would have separate applications for UsersProfiles, Questions, Tags (there's a ready one in django for this), etc. If there was a system with static pages that'd be a separate application too (there are ready ones for this purpose). You should also try and make your applications as generic as possible, so you may reuse them in other projects. There's a good presentation on reusable apps.
Just like any set of dependencies... try to find the most useful stand-alone aspects of the project and make those stand-alone apps. Other Django Apps will have higher level functionality, and reuse the parts of the lowest level apps that you have set up.
In my project, I have a calendar app with its own Event object in its models. I also have a carpool database set up, and for the departure time and the duration I use the calendar's Event object right in my RideShare tables. The carpooling database is calendar-aware, and gets all the nice .ics export and calendar views from the calendar app for 'free.'
There are some tricks to getting the Apps reusable, like naming the templates directory: project/app2/templates/app2/index.html. This lets you refer to app2/index.html from any other app, and get the right template. I picked that one up looking at the built-in reusable apps in Django itself. Pinax is a bit of a monster size-wise but it also demonstrates a nice reusable App structure.
If in doubt, forget about reusable apps for now. Put all your messages and polls in one app and get through one rev. You'll discover during the process what steps feel unnecessary, and could be broken out as something stand-alone in the future.
A good question to ask yourself when deciding whether or not to write an app is "could I use this in another project?". If you think you could, then consider what it would take to make the application as independent as possible; How can you reduce the dependancies so that the app doesn't rely on anything specific to a particular project.
Some of the ways you can do this are:
Giving each app its own urls.py
Allowing model types to be passed in as parameters rather than explicitly declaring what models are used in your views. Generic views use this principle.
Make your templates easily overridden by having some sort of template_name parameter passed in your urls.py
Make sure you can do reverse url lookups with your objects and views. This means naming your views in the urls.py and creating get_absolute_url methods on your models.
In some cases like Tagging, GenericForeignKeys can be used to associate a model in your app to any other model, regardless of whether it has ForeignKeys "looking back" at it.
I'll tell you how I am approaching such question: I usually sit with a sheet of paper and draw the boxes (functionalities) and arrows (interdependencies between functionalities). I am sure there are methodologies or other things that could help you, but my approach usually works for me (YMMV, of course).
Knowing what a site is supposed to be is basic, though. ;)