Flask что такое blueprint

Модульные приложения Flask с использованием blueprint’ов¶

Добавлено в версии 0.7.

Для чего нужны blueprint’ы?¶

Blueprint’ы во Flask могут пригодиться в случае, если нужно:

Blueprint во Flask не является подключаемым приложением, потому что это на самом деле не приложение – это набор операций, которые могут быть зарегистрированы в приложении, возможно даже не один раз. Почему бы не воспользоваться несколькими объектами приложений? Вы можете это сделать (обратитесь к разделу app-dispatch ), но ваши приложения будут иметь раздельные файлы конфигурации и будут управляться слоем WSGI.

Вместо этого, blueprint’ы предоставляют разделение на уровне Flask, позволяя использовать общий файл конфигурации приложения и могут менять объект приложения необходимым образом при регистрации. Побочным эффектом будет невозможность отменить регистрацию blueprint’а, если приложение уже было создано, если только не уничтожить целиком весь объект приложения.

Концепция blueprint’ов¶

Основная концепция blueprint’ов заключается в том, что они записывают операции для выполнения при регистрации в приложении. Flask связывает функции представлений с blueprint’ами при обработке запросов и генерировании URL’ов от одной конечной точки к другой.

Мой первый blueprint¶

Приведём пример того, как выглядит основа простейшего blueprint’а. В данном случае мы хотим реализовать blueprint, который выполняет простую отрисовку статических шаблонов:

Регистрация blueprint’ов¶

Как теперь зарегистрировать этот blueprint? Например, так:

Если теперь посмотреть на правила, зарегистрированные в приложении, то можно обнаружить следующее:

Однако, blueprint’ы можно связывать с другими местами:

И, чтобы убедиться в этом, посмотрим на правила, сгенерированные на этот раз:

Плюс ко всему, можно зарегистрировать blueprint’ы несколько раз, хотя не каждый blueprint будет работать правильно. Это зависит от того, был ли реализован blueprint’е с учётом возможности многократного монтирования.

Ресурсы blueprint’а¶

Blueprint’ы могут, кроме всего прочего, предоставлять ресурсы. Иногда может потребоваться ввести дополнительный blueprint только ради предоставления ресурсов.

Каталог ресурсов blueprint’а¶

Как и обычные приложения, blueprint’ы задуманы для размещения в отдельном каталоге. Хотя несколько blueprint’ов можно разместить в одном и том же каталоге, так делать не рекомендуется.

Для быстрого открытия ресурсов из этого каталога можно воспользоваться функцией open_resource() :

Статические файлы¶

Шаблоны¶

Если нужно выставить наружу каталог с шаблонами, это можно сделать указав параметр template_folder конструктору Blueprint :

Как и в случае статических файлов, путь может быть абсолютным или располагаться в каталоге ресурсов blueprint’а. Каталог шаблона добавляется к пути поиска шаблонов, но с меньшим приоритетом, чем каталог шаблонов самого приложения. Таким образом, можно легко заменить шаблоны blueprint’а в самом приложении.

Генерирование URL’ов¶

Наконец, если в функции представления blueprint’а или в отрисованном шаблоне нужно добавить ссылку на другую конечную точку того же blueprint’а, можно воспользоваться относительным перенаправлением, добавив префикс, состоящий только из точки:

Получится ссылка на admin.index в случае обработки текущего запроса в любой другой конечной точке blueprint’а.

Обработчики ошибок¶

Вот пример для обработки исключения «404 Page Not Found»:

Источник

BlueprintsВ¶

Flask что такое blueprint. Смотреть фото Flask что такое blueprint. Смотреть картинку Flask что такое blueprint. Картинка про Flask что такое blueprint. Фото Flask что такое blueprint

What is a blueprint?В¶

A blueprint defines a collection of views, templates, static files and other elements that can be applied to an application. For example, let’s imagine that we have a blueprint for an admin panel. This blueprint would define the views for routes like /admin/login and /admin/dashboard. It may also include the templates and static files that will be served on those routes. We can then use this blueprint to add an admin panel to our app, be it a social network for astronauts or a CRM for rocket salesmen.

Why would you use blueprints?В¶

The killer use-case for blueprints is to organize our application into distinct components. For a Twitter-like microblog, we might have a blueprint for the website pages, e.g. index.html and about.html. Then we could have another for the logged-in dashboard where we show all of the latest posts and yet another for our administrator’s panel. Each distinct area of the site can be separated into distinct areas of the code as well. This lets us structure our app as several smaller “apps” that each do one thing.

Read more about the benefits of using blueprints in “Why Blueprints” from the Flask docs.

Where do you put them?В¶

Like everything with Flask, there are many ways that we can organize our app using blueprints. With blueprints, we can think of the choice as functional versus divisional (terms I’m borrowing from the business world).

Functional structureВ¶

With a functional structure, you organize the pieces of your app by what they do. Templates are grouped together in one directory, static files in another and views in a third.

With the exception of yourapp/views/__init__.py, each of the .py files in the yourapp/views/ directory from this listing is a blueprint. In yourapp/__init__.py we would import those blueprints and register them on our Flask() object. We’ll look a little more at how this is implemented later in this chapter.

At the time of writing this, the Flask website at http://flask.pocoo.org uses this structure. Take a look for yourself on GitHub.

DivisionalВ¶

With the divisional structure, you organize the pieces of the application based on which part of the app they contribute to. All of the templates, views and static files for the admin panel go in one directory, and those for the user control panel go in another.

With a divisional structure like the app in this listing, each directory under yourapp/ is a separate blueprint. All of the blueprints are applied to the Flask() app in the top-level __init__.py

Which one is best?В¶

The organizational structure you choose is largely a personal decision. The only difference is the way the hierarchy is represented – i.e. you can architect Flask apps with either methodology – so you should choose the one that makes sense to you.

If your app has largely independent pieces that only share things like models and configuration, divisional might be the way to go. An example might be a SaaS app that lets user’s build websites. You could have blueprints in “divisions” for the home page, the control panel, the user’s website, and the admin panel. These components may very well have completely different static files and layouts. If you’re considering spinning off your blueprints as extensions or using them for other projects, a divisional structure will be easier to work with.

On the other hand, if the components of your app flow together a little more, it might be better represented with a functional structure. 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. The following listing shows a heavily abridged version of what Facebook might look like it if were built with Flask.

The blueprints in facebook/views/ are little more than collections of views rather than wholly independent components. The same static files will be used for the views in most of the blueprints. Most of the templates will extend a master template. A functional structure is a good way to organize this project.

How do you use them?В¶

Basic usageВ¶

Let’s take a look at the code for one of the blueprints from that Facebook example.

We’re using a functional structure for this Facebook example. If we were using a divisional structure, we’d want to tell Flask that the blueprint has its own template and static directories. This code block shows what that would look like.

We have now defined our blueprint. It’s time to register it on our Flask app.

Using a dynamic URL prefixВ¶

Continuing with the Facebook example, notice how all of the profile routes start with the portion and pass that value to the view. We want users to be able to access a profile by going to a URL like https://facebo-ok.com/john.doe. We can stop repeating ourselves by defining a dynamic prefix for all of the blueprint’s routes.

Blueprints let us define both static and dynamic prefixes. We can tell Flask that all of the routes in a blueprint should be prefixed with /profile for example; that would be a static prefix. In the case of the Facebook example, the prefix is going to change based on which profile the user is viewing. Whatever text they choose is the URL slug of the profile which we should display; this is a dynamic prefix.

While there aren’t any technical limitations to either method, it’s nice to have the prefixes available in the same file as the registrations. This makes it easier to move things around from the top-level. For this reason, I recommend setting url_prefix on registration.

We’re using the g object to store the profile owner and g is available in the Jinja2 template context. This means that for a barebones case all we have to do in the view is render the template. The information we need will be available in the template.

Using a dynamic subdomainВ¶

Many SaaS (Software as a Service) applications these days provide users with a subdomain from which to access their software. Harvest, for example, is a time tracking application for consultants that gives you access to your dashboard from yourname.harvestapp.com. Here I’ll show you how to get Flask to work with automatically generated subdomains like this.

For this section I’m going to use the example of an application that lets users create their own websites. Imagine that our app has three blueprints for distinct sections: the home page where users sign-up, the user administration panel where the user builds their website and the user’s website. Since these three parts are relatively unconnected, we’ll organize them in a divisional structure.

This table explains the different blueprints in this app.

URLRouteDescription
sitemaker.comsitemaker/homeJust a vanilla blueprint. Views, templates and static files for index.html, about.html and pricing.html.
bigdaddy.sitemaker.comsitemaker/siteThis blueprint uses a dynamic subdomain and includes the elements of the user’s website. We’ll go over some of the code used to implement this blueprint below.
bigdaddy.sitemaker.com/adminsitemaker/dashThis blueprint could use both a dynamic subdomain and a URL prefix by combining the techniques in this section with those from the previous section.

We can define our dynamic subdomain the same way we defined our URL prefix. Both options (in the blueprint directory or in the top-level __init__.py) are available, but once again we’ll keep the definitions in sitemaker/__init.py__.

Since we’re using a divisional structure, we’ll define the blueprint in sitemaker/site/__init__.py.

Now we have the site information from the database that we’ll use to display the user’s site to the visitor who requests their subdomain.

To get Flask to work with subdomains, we’ll need to specify the SERVER_NAME configuration variable.

A few minutes ago, as I was drafting this section, somebody in IRC said that their subdomains were working fine in development, but not in production. I asked if they had the SERVER_NAME configured, and it turned out that they had it in development but not production. Setting it in production solved their problem.

See the conversation between myself (imrobert in the log) and aplavin: http://dev.pocoo.org/irclogs/%23pocoo.2013-07-30.log

It was enough of a coincidence that I felt it warranted inclusion in the section.

You can set both a subdomain and url_prefix. Think about how we would configure the blueprint in sitemaker/dash with the URL structure from the table above.

Refactoring small apps to use blueprintsВ¶

I’d like to go over a brief example of the steps we can take to convert an app to use blueprints. We’ll start off with a typical Flask app and restructure it.

The views.py file has grown to 10,000 lines of code! We’ve been putting off refactoring it, but it’s finally time. The file contains the views for every section of our site. The sections are the home page, the user dashboard, the admin dashboard, the API and the company blog.

Step 1: Divisional or functional?В¶

This application is made up of very distinct sections. Templates and static files probably aren’t going to be shared between the user dashboard and the company blog, for example. We’ll go with a divisional structure.

Step 2: Move some files aroundВ¶

Before you make any changes to your app, commit everything to version control. You don’t want to accidentally delete something for good.

Next we’ll go ahead and create the directory tree for our new app. We can start by creating a folder for each blueprint within the package directory. Then we’ll copy views.py, static/ and templates/ in their entirety to each blueprint directory. We can then remove them from the top-level package directory.

Step 3: Cut the crapВ¶

Now we can go into each blueprint and remove the views, static files and templates that don’t apply to that blueprint. How you go about this step largely depends on how your app was organized to begin with.

The end result should be that each blueprint has a views.py file with all of the views for that blueprint. No two blueprints should define a view for the same route. Each templates/ directory should only include the templates for the views in that blueprint. Each static/ directory should only include the static files that should be exposed by that blueprint.

Make it a point to eliminate all unnecessary imports. It’s easy to forget about them, but at best they clutter your code and at worst they slow down your application.

Step 4: Blueprint…ifi…cation or something¶

This is the part where we turn our directories into blueprints. The key is in the __init__.py files. For starters, let’s take a look at the definition of the API blueprint.

Next we can register this blueprint in the U2FtIEJsYWNr package’s top-level __init__.py file.

Make sure that the routes are registered on the blueprint now rather than the app object.

Step 5: EnjoyВ¶

Now our application is far more modular than it was with one massive views.py file. The route definitions are simpler because we can group them together into blueprints and configure things like subdomains and URL prefixes once for each blueprint.

SummaryВ¶

Источник

Use a Flask Blueprint to Architect Your Applications

Flask is a very popular web application framework that leaves almost all design and architecture decisions up to the developer. In this tutorial, you’ll learn how a Flask Blueprint, or Blueprint for short, can help you structure your Flask application by grouping its functionality into reusable components.

In this tutorial, you’ll learn:

This tutorial assumes that you have some experience using Flask and that you’ve built some applications before. If you haven’t used Flask before, then check out Python Web Applications with Flask (Tutorial Series).

Free Bonus: Click here to get access to a free Flask + Python video tutorial that shows you how to build Flask web app, step-by-step.

What a Flask Application Looks Like

Let’s start by reviewing the structure of a small Flask application. You can create a small web application by following the steps in this section. To get started, you need to install the Flask Python package. You can run the following command to install Flask using pip :

Note: For more information on how to install Flask in a virtual environment and other pip options, check out Python Virtual Environments: A Primer and What Is Pip? A Guide for New Pythonistas.

After you install Flask, you’re ready to start implementing its functionality. Since Flask doesn’t impose any restrictions on project structure, you can organize your project’s code as you want. For your first application, you can use a very straightforward layout, as shown below. A single file will contain all the application logic:

The file app.py will contain the definition of the application and its views.

When you create a Flask application, you start by creating a Flask object that represents your application, and then you associate views to routes. Flask takes care of dispatching incoming requests to the correct view based on the request URL and the routes you’ve defined.

In Flask, views can be any callable (like a function) that receives requests and returns the response for that request. Flask is responsible for sending the response back to the user.

The following code block is your application’s full source code:

You can run the application with the following command:

The chosen project layout is great for very small applications, but it doesn’t scale well. As your code grows, it can become harder for you to maintain everything in a single file. So, when your application grows in size or complexity, you may want to structure your code in a different way to keep it maintainable and clear to understand. Throughout this tutorial, you’ll learn how to use a Flask Blueprint to achieve this.

What a Flask Blueprint Looks Like

Flask Blueprints encapsulate functionality, such as views, templates, and other resources. To get a taste for how a Flask Blueprint would work, you can refactor the previous application by moving the index view into a Flask Blueprint. To do so, you have to create a Flask Blueprint that contains the index view and then use it in the application.

This is what the file structure looks like for this new application:

example_blueprint.py will contain the Flask Blueprint implementation. You’ll then modify app.py to use it.

In the above code, you can see the steps common to most Flask Blueprint definitions:

The following code block shows how your application imports and uses the Flask Blueprint:

You can run the application with the following command:

How Flask Blueprints Work

In this section, you’ll learn in detail how a Flask Blueprint is implemented and used. Each Flask Blueprint is an object that works very similarly to a Flask application. They both can have resources, such as static files, templates, and views that are associated with routes.

However, a Flask Blueprint is not actually an application. It needs to be registered in an application before you can run it. When you register a Flask Blueprint in an application, you’re actually extending the application with the contents of the Blueprint.

This is the key concept behind any Flask Blueprint. They record operations to be executed later when you register them on an application. For example, when you associate a view to a route in a Flask Blueprint, it records this association to be made later in the application when the Blueprint is registered.

Making a Flask Blueprint

Let’s revisit the Flask Blueprint definition that you’ve seen previously and review it in detail. The following code shows the Blueprint object creation:

There are other optional arguments that you can provide to alter the Blueprint’s behavior:

static_folder: the folder where the Blueprint’s static files can be found

static_url_path: the URL to serve static files from

template_folder: the folder containing the Blueprint’s templates

url_prefix: the path to prepend to all of the Blueprint’s URLs

subdomain: the subdomain that this Blueprint’s routes will match on by default

url_defaults: a dictionary of default values that this Blueprint’s views will receive

root_path: the Blueprint’s root directory path, whose default value is obtained from the Blueprint’s import name

Blueprint objects also provide other methods that you may find useful:

You can learn more about using Blueprints and the Blueprint class in the Flask Blueprints Documentation.

Registering the Blueprint in Your Application

Recall that a Flask Blueprint is not actually an application. When you register the Flask Blueprint in an application, you extend the application with its contents. The following code shows how you can register the previously-created Flask Blueprint in an application:

You can customize how the Flask Blueprint extends the application by providing some parameters to register_blueprint :

Being able to do some customization at registration time, instead of at creation time, is particularly useful when you’re sharing the same Flask Blueprint in different projects.

In this section, you’ve seen how Flask Blueprints work and how you can create them and use them. In the following sections, you’ll learn how you can leverage a Flask Blueprint to architect your applications, structuring them into independent components. In some cases, it’s also possible for you to reuse these components in different applications to reduce development time!

How to Use Flask Blueprints to Architect Your Application’s Code

In this section, you’re going to see how you can refactor an example application using a Flask Blueprint. The example application is an e-commerce site with the following features:

You don’t need to care much about the details of the implementation. Instead, you’ll focus mainly on how a Flask Blueprint can be used to improve the application’s architecture.

Understanding Why Project Layout Matters

Remember, Flask does not enforce any particular project layout. It’s completely feasible to organize this application’s code as follows:

This application’s code is organized using these directories and files:

Also, if you have just one file for the application logic, then you would end up with a very large app.py that mixes code that’s nearly unrelated. This can make it hard for you to navigate and maintain the script.

What’s more, large code files are a source of conflicts when you’re working in a team, since everybody will be making changes to the same file. These are just a few reasons why the previous layout is only good for very small applications.

Organizing Your Projects

Instead of structuring the application using the previous layout, you can leverage a Flask Blueprint to split the code into different modules. In this section, you’ll see how to architect the previous application to make Blueprints that encapsulate related functionality. In this layout, there are five Flask Blueprints:

If you use a separate directory for each Flask Blueprint and its resources, then the project layout would look as follows:

Let’s see the Products Blueprint implementation in products/products.py :

Now you can move the rest of your code’s functionality to the corresponding Flask Blueprint. In other words, you can create Blueprints for API, authentication, cart, and general functionality. Once you’ve done so, the only code left in app.py will be code that deals with application initialization and Flask Blueprint registration:

Including Templates

If you set the template_folder argument in a Blueprint’s creation, then its templates folder is added to the application’s template search path when the Flask Blueprint is registered. However, if there are duplicated file paths under different directories that are part of the template search path, then one will take precedence, depending on their registration order.

For example, if a view requests the template view.html and there are files with this same name in different directories in the template search path, then one of these will take precedence over the other. Since it may be hard to remember the precedence order, it’s best to avoid having files under the same path in different template directories. That’s why the following structure for the templates in the application makes sense:

At first, it may look redundant to have the Flask Blueprint name appear twice:

As a final note, it’s important to know that templates in the application’s template directory have greater precedence than those inside the Blueprint’s template directory. This can be useful to know if you want to override Flask Blueprint templates without actually modifying the template file.

For example, if you wanted to override the template products/view.html in the Products Blueprint, then you can accomplish this by creating a new file products/view.html in the application templates directory:

Providing Functionality Other Than Views

So far, you’ve only seen Blueprints that extend applications with views, but Flask Blueprints don’t have to provide just views! They can extend applications with templates, static files, and template filters. For example, you could create a Flask Blueprint to provide a set of icons and use it across your applications. This would be the file structure for such a Blueprint:

The static folder contains the icon files and icons.py is the Flask Blueprint definition.

This is how icons.py might look:

This code defines the icons_bp Flask Blueprint that exposes the files in the static directory under the /icons/ URL. Note that this Blueprint does not define any route.

When you can create Blueprints that package views and other types of content, you make your code and assets more reusable across your applications. You’ll learn more about Flask Blueprint reusability in the following section.

How to Use Flask Blueprints to Improve Code Reuse

Besides code organization, there’s another advantage to structuring your Flask application as a collection of independent components. You can reuse these components even across different applications! For example, if you created a Flask Blueprint that provides functionality for a contact form, then you can reuse it in all your applications.

You can also leverage Blueprints created by other developers to accelerate your work. While there’s no centralized repository for existing Flask Blueprints, you can find them using the Python Package Index, GitHub Search, and web search engines. You can learn more about searching PyPI packages in What Is Pip? A Guide for New Pythonistas.

There are various Flask Blueprints and Flask Extensions (which are implemented using Blueprints) that provide functionality that you may find useful:

Instead of coding your application from scratch, you may consider searching for an existing Flask Blueprint or Extension that you can reuse. Leveraging third-party Blueprints and Extensions can help you to reduce development time and keep your focus on your application’s core logic!

Conclusion

In this tutorial, you’ve seen how Flask Blueprints work, how to use them, and how they can help you to organize your application’s code. Flask Blueprints are a great tool for dealing with application complexity as it increases.

You’ve learned:

You can use what you’ve learned in this tutorial to start organizing your applications as a set of blueprints. When you architect your applications this way, you’ll improve code reuse, maintainability, and teamwork!

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Flask что такое blueprint. Смотреть фото Flask что такое blueprint. Смотреть картинку Flask что такое blueprint. Картинка про Flask что такое blueprint. Фото Flask что такое blueprint

About Miguel Garcia

Flask что такое blueprint. Смотреть фото Flask что такое blueprint. Смотреть картинку Flask что такое blueprint. Картинка про Flask что такое blueprint. Фото Flask что такое blueprint Flask что такое blueprint. Смотреть фото Flask что такое blueprint. Смотреть картинку Flask что такое blueprint. Картинка про Flask что такое blueprint. Фото Flask что такое blueprint

Miguel has been working in different roles in IT for over a decade. He has a MSc. degree in Computer Science and enjoys building things using open source technologies.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Flask что такое blueprint. Смотреть фото Flask что такое blueprint. Смотреть картинку Flask что такое blueprint. Картинка про Flask что такое blueprint. Фото Flask что такое blueprint

Flask что такое blueprint. Смотреть фото Flask что такое blueprint. Смотреть картинку Flask что такое blueprint. Картинка про Flask что такое blueprint. Фото Flask что такое blueprint

Flask что такое blueprint. Смотреть фото Flask что такое blueprint. Смотреть картинку Flask что такое blueprint. Картинка про Flask что такое blueprint. Фото Flask что такое blueprint

Flask что такое blueprint. Смотреть фото Flask что такое blueprint. Смотреть картинку Flask что такое blueprint. Картинка про Flask что такое blueprint. Фото Flask что такое blueprint

Flask что такое blueprint. Смотреть фото Flask что такое blueprint. Смотреть картинку Flask что такое blueprint. Картинка про Flask что такое blueprint. Фото Flask что такое blueprint

Master Real-World Python Skills With Unlimited Access to Real Python

Flask что такое blueprint. Смотреть фото Flask что такое blueprint. Смотреть картинку Flask что такое blueprint. Картинка про Flask что такое blueprint. Фото Flask что такое blueprint

Join us and get access to hundreds of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

Flask что такое blueprint. Смотреть фото Flask что такое blueprint. Смотреть картинку Flask что такое blueprint. Картинка про Flask что такое blueprint. Фото Flask что такое blueprint

Join us and get access to hundreds of tutorials, hands-on video courses, and a community of expert Pythonistas:

Real Python Comment Policy: The most useful comments are those written with the goal of learning from or helping out other readers—after reading the whole article and all the earlier comments. Complaints and insults generally won’t make the cut here.

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *