Only this pageAll pages
Powered by GitBook
1 of 58

v1.4

Loading...

Prologue

Loading...

Loading...

Loading...

Loading...

What's New

Loading...

Loading...

Upgrade Guide

Loading...

The Basics

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

The Craft Command

Loading...

Loading...

Loading...

Architectural Concepts

Loading...

Loading...

Loading...

Advanced

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Useful Features

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Security

Loading...

Loading...

Loading...

Orator ORM

Loading...

Managers and Drivers

Loading...

Loading...

Loading...

Official Packages

Loading...

Loading...

Loading...

Release Cycle

Release Cycle

Introduction

The Masonite framework itself follows the RomVer versioning schema which is PARADIGM.MAJOR.MINOR although all Masonite packages follow the SemVer versioning schema which is MAJOR.MINOR.FEATURE/BUGFIX.

This means that a framework version of 1.3.20 will have breaking changes with version 1.4.0.

Reasoning for RomVer over SemVer

The Masonite main repository (the MiraFramework/masonite repository) contains only the basic file structure of the application. All of the core framework functionality is inside the MasoniteFramework/core repository which can be updated as much as every day or once per month and therefore will follow normal SemVer. Because MiraFramework/masonite does not require major updates, we can follow RomVer nicely and keep the versioning number artificially lower. Any major updates to this repsository will likely just be file structure changes which should rarely happen unless there are major architectural changes.

Cycle

Masonite is currently on a 1 month major release cycle. This means that once every month will be a new 1.x release. This 1 month release cycle will continue until Masonite has reached a release that is stable enough to move far into the future with that releases architecture.

Once this stable release has been achieved, Masonite will move to a 6 month major release cycle with minor releases as often as every few days to as much as every few months.

Scheduled Releases

Creating Releases

Masonite is made up of three different repositories. There is

  • The main repository where development is done on the repo that installs on developer's systems.

  • The core repository which is where the main Masonite pip package is located.

  • The cli repository where the craft command tool is located.

Major 1 month releases will be released on or after the release date when all repositories are able to be released at the same time, as well as passing all tests.

Whenever the MasoniteFramework/cli and MasoniteFramework/core repositories are released on Github, Travis CI will run tests and automatically deploy to PyPi. These major version numbers should correspond to the version of Masonite they support. For example, if the MasoniteFramework/masonite releases to version 1.4, MasoniteFramework/core should bump up to 1.4.x regardless of changes.

Once all three repositories are ready for release, they will all be released on GitHub under the respective new version numbers.

Contributing Guide

Contributing Guide

Introduction

When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners or contributors of this repository before making a change.

Please note we have a code of conduct, please follow it in all your interactions with the project.

Getting Started

The framework has three main parts.

  • This official MasoniteFramework/masonite repository is where most work will be done, primarily in the develop or release branches. This is the main repository that will install when creating new projects using the craft new command.

  • The `MasoniteFramework/core repository where the main masonite pip package lives.

    • This is where the from masonite ... module lives.

  • The MasoniteFramework/craft repository where the craft command lives

Getting this repository up and running to be edited

This repo is simple and will be able to be installed following the installation instruction in the README.

  • Fork the MasoniteFramework/masonite repo.

  • Clone that repo into your computer:

    • git clone http://github.com/your-username/masonite.git

  • Checkout the current release branch (example: develop)

  • You should now be on a develop local branch.

  • run git pull origin develop to get the current release version.

  • From there simply create your feature branches (change-default-orm) and make your desired changes.

  • Push to your origin repository:

    • git push origin change-default-orm

  • Open a pull request and follow the PR process below

Editing the Masonite core repository

The trick to this is that we need it to be pip installed and then quickly editable until we like it, and then pushed back to the repo for a PR. Do this only if you want to make changes to the core Masonite package

To do this just:

  • Fork the MasoniteFramework/core repo,

  • Clone that repo into your computer:

    • git clone http://github.com/your-username/core.git

  • Activate your masonite virtual environment (optional)

    • Go to where you installed masonite and activate the environment

  • While inside the virtual environment, cd into the directory you installed core.

  • Run pip install . from inside the masonite-core directory. This will install masonite as a pip package.

  • Any changes you make to this package just push it to your feature branch on your fork and follow the PR process below.

Editing the craft repository (craft commands)

Craft commands make up a large part of the workflow for Masonite. Follow these instructions to get the masonite-cli package on your computer and editable.

  • Fork the MasoniteFramework/craft repo,

  • Clone that repo into your computer:

    • git clone http://github.com/your-username/craft.git

  • Activate your masonite virtual environment (optional)

    • Go to where you installed masonite and activate the environment

  • While inside the virtual environment, cd into the directory you installed cli

  • Run pip install --editable . from inside the masonite-cli directory. This will install cli (which contains the craft commands) as a pip package but also keep a reference to the folder so you can make changes freely to craft commands while not having to worry about continuously reinstalling it.

  • Any changes you make to this package just push it to your feature branch on your fork and follow the PR process below.

Comments

Comments are a vital part of any repository and should be used where needed. It is important not to overcomment something. If you find you need to constantly add comments, you're code may be too complex. Code should be self documenting (with clearly defined variable and method names)

Types of comments to use

There are 3 main type of comments you should use when developing for Masonite:

Module Docstrings

All modules should have a docstring at the top of every module file and should look something like:

Method and Function Docstrings

All methods and functions should also contain a docstring with a brief description of what the module does

For example:

Code Comments

If you're code MUST be complex enough that future developers will not understand it, add a # comment above it

For normal code this will look something like:

Flagpole Comments

Flag pole comments are a fantastic way to give developers an inside to what is really happening and for now should only be reserved for configuration files. A flag pole comment gets its name from how the comment looks

It's important to note that there should have exactly 75 - above and below the header and have a trailing | at the bottom of the comment.

Pull Request Process

  1. You should open an issue before making any pull requests. Not all features will be added to the framework and some may be better off as a third party package. It wouldn't be good if you worked on a feature for several days and the pull request gets rejected for reasons that could have been discussed in an issue.

  2. Ensure any changes are well commented and any configuration files that are added have a flagpole comment on the variables it's setting.

  3. Update the README.md and MasoniteFramework/docs repo with details of changes to the interface, this includes new environment variables, new file locations, container parameters etc.

  4. You must add unit testing for any changes made. Of the three repositories listed above, only the cli and core repos require unit testing.

  5. The PR must pass the Travis CI build. The Pull Request can be merged in once you have a success review of two other collaborators, or the feature maintainer for your specific feature improvement or the repo owner.

Code of Conduct

Our Pledge

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.

Our Standards

Examples of behavior that contributes to creating a positive environment include:

  • Using welcoming and inclusive language

  • Being respectful of differing viewpoints and experiences

  • Gracefully accepting constructive criticism

  • Focusing on what is best for the community

  • Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

  • The use of sexualized language or imagery and unwelcome sexual attention or

    advances

  • Trolling, insulting/derogatory comments, and personal or political attacks

  • Public or private harassment

  • Publishing others' private information, such as a physical or electronic

    address, without explicit permission

  • Other conduct which could reasonably be considered inappropriate in a

    professional setting

Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at idmann509@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

Attribution

The main repository which is MasoniteFramework/masonite does not have a corresponding PyPi package and is only for installing new Masonite projects. See the craft new command under documentation.

Increase the version numbers in any example files and the README.md to the new version that this Pull Request would represent. The versioning scheme we use is for both core and cli or for the main Masontie repo.

This Code of Conduct is adapted from the , version 1.4, available at

The Craft Command
''' This is a module to add support for Billing users '''
from masonite.request import Request
...
def some_function(self):
    ''' This is a function that does x action. 
        Then give an exmaple of when to use it 
    '''
    ... code ...
# This code performs a complex task that may not be understood later on
# You can add a second line like this
complex_code = 'value'

perform_some_complex_task()
'''
|--------------------------------------------------------------------------
| A Heading of The Setting Being Set
|--------------------------------------------------------------------------
|
| A quick description
|
'''

SETTING = 'some value'
You can read about how the framework flows, works and architectural concepts here
SemVer
RomVer
Contributor Covenant
http://contributor-covenant.org/version/1/4

Masonite 1.3

Masonite 1.3

Introduction

Masonite 1.3 comes with a plethora of improvements over previous versioning. This version brings new features such as Queue and Mail drivers as well as various bug fixes.

1. Fixed infinite redirection

Previously when a you tried to redirect using the Request.redirect() method, Masonite would sometimes send the browser to an infinite redirection. This was because masonite was not resetting the redirection attributes of the Request class.

2. Fixed browser content length

Previously the content length in the request header was not being set correctly which led to the gunicorn server showing a warning that the content length did not match the content of the output.

3. Changed how request input data is retrieved

Previously the Request class simply got the input data on both POST and GET requests by converting the wsgi.input WSGI parameter into a string and parsing. All POST input data is now retrieved using FieldStorage which adds support for also getting files from multipart/formdata requests.

4. Added Upload drivers

You may now simply upload images to both disk and Amazon S3 storage right out of the box. With the new UploadProvider service provider you can simply do something like:

<html>
  <body>
      <form action="/upload" method="POST" enctype="multipart/formdata">
        <input type="file" name="file">
      </form>
  </body>
</html>
def show(self, Upload):
    Upload.store(Request.input('file'))

As well as support for Amazon S3 by setting the DRIVER to s3.

5. Added several helper functions

These helper functions are added functions to the builtin Python functions which can be used by simply calling them as usual:

def show(self):
    return view('welcome')

6. Added a way to have global template variables

Very often you will want to have a single variable accessible in all of your views, such as the Request object or other class. We can use the new View class for this and put it in it's own service provider:

def boot(self, View, Request):
    View.share({'request': Request})

7. Middleware is now resolved by the container

You can now specify anything that is in the container in your middleware constructor and it will be resolved automatically from the container

8. Added new domain method to the Get and Post classes

Specify the subdomain you want to target with your route. It's common to want to have separate routes for your public site and multi-tenant sites. This will now look something like:

Get().domain('test').route('/dashboard', 'DashboardController@show')

9. Added new module method to Get and Post routes

By default, masonite will look for routes in the app/http/controllers namespace but you can change this for individual routes:

Get().module('thirdpary.routes').route('/dashboard', 'DashboardController@show')

This will look for the controller in the thirdparty.routes module.

10. Added Queues and Jobs

Introduction and Installaton

Masonite is the rapid application Python development framework that strives for: beautiful and elegant syntax, actual batteries included with a lot of out of the box functionality, and extremely extendable. Masonite works hard to be fast and easy from install to deployment so developers can go from concept to creation in as quick and efficiently as possible. Try it once and you’ll fall in love.

Some Notable Features Shipped With Masonite

  • Easily send emails with the Mail Provider and the SMTP and Mailgun drivers.

  • Send websocket requests from your server with the Broadcast Provider and Pusher and Ably drivers.

  • IOC container and auto resolving dependency injection.

  • Service Providers to easily add functionality to the framework.

  • Extremely simple static files configured and ready to go.

  • Active Record style ORM called Orator.

  • An extremely useful command line tool called craft commands.

These, among many other features, are all shipped out of the box and ready to go. Use what you need when you need it.

Requirements

In order to use Masonite, you’ll need:

  • Python 3.4+

  • Pip

Linux

If you are running on a Linux flavor, you’ll need the Python dev package. You can download this package by running:

Or you may need to specify your python3.x-dev version:

Installation

Masonite works at being simple to install and get going. We use a simple command line that will become your best friend. You’ll never want to develop again without it. We call it the craft command line tool.

We can download our craft command line tool by just running:

You may have to use sudo if you are on a UNIX machine

Great! We are now ready to create our first project. We should have the new craft command. We can check this by running:

This should show a list of command options. If it doesn't then try closing your terminal and reopening it or running it with sudo if you are on a UNIX machine. We are currently only interested in the craft new command. To create a new project just run:

This will get the latest Masonite project template and unzip it for you. We just need to go into our new project directory and install the dependencies in our requirements.txt file.

You can optionally create a virtual environment if you don't want to install all of masonite's dependencies on your systems Python. If you use virtual environments then create your virtual environment by running:

or if you are on Windows:

Now lets install our dependencies. We can do this simply by using a craft command:

This installs all the required dependencies of Masonite, creates a .env file for us, generates a new secret key, and puts that secret key in our .env file. After it’s done we can just run the server by using another craft command:

Notice how we never imported anything from the module or Service Container. See the documentation for a more exhaustive list

Which will target test.example.com/dashboard and not example.com/dashboard. Read more about subdomains in the documentation.

Masonite now ships with a QueueManager class which can be used to build queue drivers. Masonite ships with an async driver which sends jobs to a background thread. These queues can process Jobs which ca be created with the new craft job command. See the documentation for more information.

Congratulations! You’ve setup your first Masonite project! Keep going to learn more about how to use Masonite to build your applications. You can learn more about craft by reading documentation.

Helper Functions
Routing
Queues and Jobs
$ sudo apt-get install python-dev
$ sudo apt-get install python3.6-dev
$ pip install masonite-cli
$ craft
$ craft new project_name
$ cd project_name
$ python -m venv venv
$ source venv/bin/activate
$ python -m venv venv
$ ./venv/Scripts/activate
$ craft install
$ craft serve
The Craft Command

Introduction

Masonite is the rapid application Python development framework that strives for: beautiful and elegant syntax, actual batteries included with a lot of out of the box functionality, and extremely extendable. Masonite works hard to be fast and easy from install to deployment so developers can go from concept to creation in as quick and efficiently as possible. Try it once and you’ll fall in love.

Some Notable Features Shipped With Masonite

  • Easily send emails with the Mail Provider and the SMTP and Mailgun drivers.

  • Send websocket requests from your server with the Broadcast Provider and Pusher and Ably drivers.

  • IOC container and auto resolving dependency injection.

  • Service Providers to easily add functionality to the framework.

  • Extremely simple static files configured and ready to go.

  • Active Record style ORM called Orator.

  • An extremely useful command line tool called craft commands.

These, among many other features, are all shipped out of the box and ready to go. Use what you need when you need it.

Requirements

In order to use Masonite, you’ll need:

  • Python 3.4+

  • Pip

Linux

If you are running on a Linux flavor, you’ll need the Python dev package. You can download this package by running:

Or you may need to specify your python3.x-dev version:

Installation

Masonite works at being simple to install and get going. We use a simple command line that will become your best friend. You’ll never want to develop again without it. We call it the craft command line tool.

We can download our craft command line tool by just running:

You may have to use sudo if you are on a UNIX machine

Great! We are now ready to create our first project. We should have the new craft command. We can check this by running:

This should show a list of command options. If it doesn't then try closing your terminal and reopening it or running it with sudo if you are on a UNIX machine. We are currently only interested in the craft new command. To create a new project just run:

This will get the latest Masonite project template and unzip it for you. We just need to go into our new project directory and install the dependencies in our requirements.txt file.

You can optionally create a virtual environment if you don't want to install all of masonite's dependencies on your systems Python. If you use virtual environments then create your virtual environment by running:

or if you are on Windows:

Now lets install our dependencies. We can do this simply by using a craft command:

This installs all the required dependencies of Masonite, creates a .env file for us, generates a new secret key, and puts that secret key in our .env file. After it’s done we can just run the server by using another craft command:

Congratulations! You’ve setup your first Masonite project! Keep going to learn more about how to use Masonite to build your applications. You can learn more about craft by reading documentation.

$ sudo apt-get install python-dev
$ sudo apt-get install python3.6-dev
$ pip install masonite-cli
$ craft
$ craft new project_name
$ cd project_name
$ python -m venv venv
$ source venv/bin/activate
$ python -m venv venv
$ ./venv/Scripts/activate
$ craft install
$ craft serve
The Craft Command

How To Contribute

How To Contribute

Introduction

There are plenty of ways to contribute to open source. Many of which don't even rely on writing code. A great open source project should have excellent documentation and have as little bugs as possible. Below I will explain how to contribute to this project in different ways.

This is not an exhaustive list and not the only ways to contribute but they are the most common. If you know of other ways to contribute then please let us know.

Contributing to Development

Comment the Code

If you don't want to touch the code and instead want to just look at it and figure it out, contribute some comments! Comments are an excellent way for future developers to read and understand the framework. Masonite strives on being extremely commented. Although most of the code itself does not need to be commented, some of the classes, modules, methods and functions do (although a lot of them already are).

Comments don't affect the working code so if you want to get used to contributing to open source or you just don't quite understand what a class method is doing or you are afraid of contributing and breaking the project (there are tests) then contributing comments is right for you!

Write Tests

Contribute to Tutorials

Plus there will be fantastic tutorials out there for beginners to find and watch and you could also build a following off the back of Masonite.

Fix the Documentation

Report Bugs

Squash Bugs

Build a Community

If you have a large following on any social media or no following at all, you can contribute by trying to build up a following around Masonite. Any open source project requires an amazing community around the framework. You can either build up a community personally and be the leader of that community or you can simply send them to Masonite's GitHub repository where we can build up a community around there.

Build Community Software Around Masonite

Answer Questions from the Community

Questions will come in eventually either through the GitHub issues or through websites like StackOverflow. You could make it a priority to be the first to answer these peoples questions or if you don't know the answer you can redirect one of the core maintainers or contributors to the question so we can answer it further.

Review Code on Pull Requests

Discuss Issues

Every now and then will be a requires discussion label on an issue or pull request. If you see this label then be sure to add your thoughts on an issue. All issues are open for discussion and Masonite strives off of developer input so feel free to enter a discussion.

Of course the project requires contributions to the main development aspects but it's not the only way. But if you would like to contribute to development then a great way to get started is to simply read through this documentation. Get acquainted with how the framework works, how and work and read the documentation starting with the , then the and finally the .

It would also be good to read about the to get familiar with how Masonite does releases (SemVer and RomVer).

The require testing (The main repository does not). If you want to search through all the tests in the tests directories of those repositories and write additional tests and use cases then that will be great! There are already over 100 tests but you can always write more. With more testing comes more stability. Especially as people start to contribute to the project. Check the tests that are already there and write any use cases that are missing. These tests can be things such as special characters in a url or other oddities that may not have been thought of when using TDD for that feature.

Once familiar with the project (by either contributing or by building application using the framework) it would be excellent if you could write or record tutorials and put them on or . In order for the framework to be successful, it needs to have a plethora of documentation even outside of this documentation. It needs to have notoriety and if people are seeing the framework pop up in their favorite locations they will be more inclined to use the framework and contribute to it as well.

This documentation is fantastic but there are spots where it could be improved. Maybe we haven't explained something fully or something just doesn't make sense to you. Masonite uses to host it's documentation and with that you are able to comment directly on the documentation which will start a discussion between you and the documentation collaborators. So if you want to cycle through the documentation page by page and get acquainted with the framework but at the same time contribute to the documentation, this is perfect for you.

If you just don't want to contribute code to the main project you may instead simply report bugs or improvements. You can go ahead and build any of your applications as usual and report any bugs you encounter to the issues page.

Look at the issues page on for any issues, bugs or enhancements that you are willing to fix. If you don't know how to work on them, just comment on the issue and Joseph Mancuso or other core contributors will be more than happy explaining step by step on how you can go about fixing or developing that issue.

Another idea is to use Masonite to build applications such as a screencast website like or an official Masonite website or even a social network around Masonite. Every great framework needs it's "ecosystem" so you may be apart of that buy building these applications with the Masonite branding and logos. Although copying the branding requires an OK from Joseph Mancuso, as long as the website was built with Masonite and looks clean it shouldn't be a problem at all.

Most pull requests will sit inside GitHub for a few days while it gets quality tested. The main develop branch pull requests could sit there for as long as 6 months and will only be merged in on releases. With that being said, you can look at the file changes of these pull requests and ensure they meet the community guidelines, the API is similar to other aspects of the project and that they are being respectful and following pull requests rules in accordance with the documentation.

Controllers
Routing
Architectural Concepts
Request Lifecycle
Service Providers
Service Container
Release Cycle
Masonite pip packages
Medium
YouTube
Gitbook.com
GitHub.com
GitHub.com
LaraCasts.com
Contributing Guide

Masonite 1.4

Masonite 1.4

Introduction

Broadcast Support

Caching

Masonite now has a built in caching class that you can use to either cache forever or cache for a specific amount of time.

Template Caching

Templates may have a lot of logic that are only updated every few minutes or even every few months. With template caching you can now cache your templates anywhere from every few seconds to every few years. This is an extremely powerful caching technique that will allow your servers to run less intensively and easily increase the performance of your application.

If a page gets hit 100 times every second then you can cache for 5, 10 or 15 seconds at a time to lessen the load on your server.

This feature only activates if you have the CacheProvider loaded in your PROVIDERS list. If you try to use these features without that provider then you will be hit with a RequiredContainerBindingNotFound exception letting you know you are missing a required binding from a service provider. This provider comes out of the box in Masonite 1.4.

PEP 8 Standards

We have also updated the code to closely conform to PEP 8 standards.

Added a New Folder and Configuration File

Because of the caching features, we have added a bootstrap/cache folder where all caching will be put but you can change this in the new config/cache.py file.

Added Contracts

Masonite 1.4 brings the idea of contracts which are very similar to interfaces in other languages. Contracts ensure that a driver or manager inherits has the same functionality across all classes of the same type.

Added CSRF Protection

Cross-Site Request Forgery is a crucial security milestone to hit and Masonite 1.4 brings that ability. With a new Service Provider and middleware, we can now add a simple {{ csrf_field|safe }} to our forms and ensure we are protected from CSRF attacks.

Changed Managers

Managers were very redundant before this release so we made it much easier to create managers with 2 simple class attributes instead of the redundant method. Managers are used to manage features and drivers to Masonite.

Middleware is now resolved by the container

Now the constructor of all middleware is resolved by the container. This means you may use the IOC dependency injection techniques like controller methods and drivers.

Fixed unused imports

There were two unused imports in the models that Masonite created. These have been removed completely.

Masonite 1.4 brings several new features to Masonite. These features include caching, template caching, websocket support with Masonite calls Broadcasting and much more testing to make Masonite as stable as possible. If you would like to contribute to Masonite, please read the and the documentation.

If you are upgrading from Masonite 1.3 then please read the documentation.

We recognize that in order for frameworks to keep up with modern web application, they require real time broadcasting. Masonite 1.4 brings basic broadcasting of events to masonite and comes with two drivers out of the box: pusher and ably. If you'd like to create more drivers then you can do so easily by reading the documentation. If you do create a driver, please consider making it available on PyPi so others can install it into their projects or open an issue on GitHub and make to add it to the built in drivers.

Contributing Guide
How To Contribute
Masonite 1.3 to 1.4
About Drivers

Masonite 1.3 to 1.4

Masonite 1.3 to 1.4

Introduction

Masonite 1.4 brings several new features and a few new files. This is a very simple upgrade and most of the changes were done in the pip package of Masonite. The upgrade from 1.3 to 1.4 should take less than 10 minutes

Requirements.txt File

This requirement file has the masonite>=1.3,<=1.3.99 requirement. This should be changed to masonite>=1.4,<=1.4.99. You should also run pip install --upgrade -r requirements.txt to upgrade the Masonite pip package.

New Cache Folder

There is now a new cache folder under bootstrap/cache which will be used to store any cached files you use with the caching feature. Simply create a new bootstrap/cache folder and optionally put a .gitignore file in it so your source control will pick it up.

New Cache and Broadcast Configuration

3 New Service Providers

Masonite comes with a lot of out of the box functionality and nearly all of it is optional but Masonite 1.4 ships with three new providers. Most Service Providers are not ran on every request and therefore does not add significant overhead to each request. To add these 3 new Service Providers simple add these to the bottom of the list of framework providers:

PROVIDERS = [
    # Framework Providers
    ...
    'masonite.providers.HelpersProvider.HelpersProvider',
    'masonite.providers.QueueProvider.QueueProvider',

    # 3 New Providers in Masonite 1.4
    'masonite.providers.BroadcastProvider.BroadcastProvider',
    'masonite.providers.CacheProvider.CacheProvider',
    'masonite.providers.CsrfProvider.CsrfProvider',

    # Third Party Providers

    # Application Providers
    'app.providers.UserModelProvider.UserModelProvider',
    'app.providers.MiddlewareProvider.MiddlewareProvider',
]

Note however that if you add the CsrfProvider then you will also need the CSRF middleware which is new in Masonite 1.4. Read the section below to add the middleware

CSRF and CSRF Middleware

Masonite 1.4 adds CSRF protection. So anywhere there is any POST form request, you will need to add the {{ csrf_field|safe }} to it. For example:

<form action="/dashboard" method="POST">
    {{ csrf_field|safe }}
    <input type="text" name="first_name">
</form>

Lastly, put that middleware into the HTTP_MIDDLEWARE list inside config/middleware.py like so:

HTTP_MIDDLEWARE = [
    'app.http.middleware.LoadUserMiddleware.LoadUserMiddleware',
    'app.http.middleware.CsrfMiddleware.CsrfMiddleware',
]

Changes to Database Configuration

from config import database

database.db.table(...)

should now be:

from config import database

database.DB.table(...)

with this change

Masonite 1.4 brings a new config/cache.py and config/broadcast.py files. These files can be found on the page and can be copied and pasted into your project. Take a look at the new file and the file. Just copy and paste those configuration files into your project.

This type of protection prevents cross site forgery. In order to activate this feature, we also need to add the . Copy and paste the middleware into your project under the app/http/middleware/CsrfMiddleware.py file.

There has been a slight change in the constants used in the file. Mainly just for consistency and coding standards. Your file may have some slight changes but this change is optional. If you do make this change, be sure to change any places in your code where you have used the Orator Query Builder. For example any place you may have:

GitHub
config/cache.py
config/broadcast.py
CSRF middleware
config/database.py

Routing

Routing

Introduction

Masonite Routing is an extremely simple but powerful routing system that at a minimum takes a url and a controller. Masonite will take this route and match it against the requested route and execute the controller on a match.

All routes are created inside routes/web.py and are contained in a ROUTES constant. All routes consist of either a Get() route or a Post() route. At the bare minimum, a route will look like:

Get().route('/url/here', 'WelcomeController@show')

Most of your routes will consist of a structure like this. All URI’s should have a preceding /. Routes that should only be executed on Post requests (like a form submission) will look very similar:

Post().route('/url/here', 'WelcomeController@store')

Notice the controller here is a string. This is a great way to specify controllers as you do not have to import anything into your web.py file. All imports will be done in the backend. More on controllers later.

If you wish to not use string controllers and wish to instead import your controller then you can do so by specifying the controller as well as well as only passing a reference to the method. This will look like:

from app.http.controllers.DashboardController import DashboardController

ROUTES = [
    Get().route('/url/here', DashboardController().show)
]

It’s important here to recognize that we initialized the controller but only passed a reference to the method and did not actually call the method. This is so Masonite can pass parameters into the method when it executes the route.

Route Options

There are a few methods you can use to enhance your routes. Masonite typically uses a setters approach to building instead of a parameter approach so to add functionality, we can simply attach more methods.

Named Routes

We can name our routes so we can utilize these names later when or if we choose to redirect to them. We can specify a route name like so:

Get().route('/dashboard', 'DashboardController@show').name('dashboard')

It is good convention to name your routes since route url’s can change but the name should always stay the same.

Route Middleware

Middleware is a great way to execute classes, tasks or actions either before or after requests. We can specify middleware specific to a route after we have registered it in our config/middleware.py file but we can go more in detail in the middleware documentation. To add route middleware we can use the middleware method like so:

Get().route('/dashboard', 'DashboardController@show').middleware('auth', 'anothermiddleware')

This middleware will execute either before or after the route is executed depending on the middleware.

Deeper Module Controllers

All controllers are located in app/http/controllers but sometimes you may wish to put your controllers in different modules deeper inside the controllers directory. For example, you may wish to put all your product controllers in app/http/controllers/products or all of your dashboard controllers in app/http/controllers/users. In order to access these controllers in your routes we can simply specify the controller using our usual dot notation:

Get().route('/dashboard', 'users.DashboardController@show')

Change Controller Modules

Controllers are defaulted to the app/http/controllers directory but you may wish to completely change the directory for a certain route. We can change this by using the .module() method:

Get().module('thirdparty.package').route('/dashboard', 'users.DashboardController@show')

This will look for the controller in thirdparty.package.users module instead of the normal app.http.controllers module.

Route Parameters

Very often you’ll need to specify parameters in your route in order to retrieve information from your URI. These parameters could be an id for the use in retrieving a certain model. Specifying route parameters in Masonite is very easy and simply looks like:

Get().route('/dashboard/@id', 'Controller@show')

That’s it. This will create a dictionary inside the Request object which can be found inside our controllers.

In order to retrieve our parameters from the request we can use the param method on the Request object like so:

def show(self, Request):
    Request.param('id')

Route Parameter Options

Sometimes you will want to make sure that the route parameter is of a certain type. For example you may want to match a URI like /dashboard/1 but not /dashboard/joseph. In order to do this we simply need to pass a type to our parameter. If we do not specify a type then our parameter will default to matching all alphanumeric and underscore characters.

Get().route('/dashboard/@id:int', 'Controller@show')

This will match all integers but not strings. So for example it will match /dashboard/10283 and not /dashboard/joseph

If we want to match all strings but not integers we can pass:

Get().route('/dashboard/@id:string', 'Controller@show')

This will match /dashboard/joseph and not /dashboard/128372. Currently only the integer and string types are supported.

Subdomain Routing

You may wish to only render routes if they are on a specific subdomain. For example you may want example.com/dashboard to route to a different controller than joseph.example.com/dashboard. To do this we can use the .domain() method on our routes like so:

Get().domain('joseph').route('/dashboard', 'Controller@show')

This route will match to joseph.example.com/dashboard but not to example.com/dashboard or test.example.com/dashboard.

It may be much more common to match to any subdomain. For this we can pass in an asterisk instead.

Get().domain('*').route('/dashboard', 'Controller@show')

This will match all subdomains such as test.example.com/dashboard, joseph.example.com/dashboard but not example.com/dashboard.

If a match is found, it will also add a subdomain parameter to the Request class. We can retrieve the current subdomain like so:

def show(self, Request):
    print(Request.param('subdomain'))

Controllers

Controllers

Introduction

Controllers are a vital part of Masonite and is mainly what differs it from other Python frameworks that implement the MVC structure differently. Controllers are simply classes with methods. These methods take a self parameter which is the normal self that Python class methods require. Controller methods can be looked at as function based views if you are coming from django as they are simply methods inside a class and function the exact same way.

Controllers have an added benefit over straight function based views as the developer has access to to a full class they can manipulate however they want but are also not limiting like Django's class based views. They provide a lot of flexibility.

Defining a Controller

Its very easy to create a controller with Masonite with the help of our craft command tool. We can simply create a new file inside app/http/controllers, name the class the same name as the file and then create a class with methods. We can also use the craft controller command to do all of that for us which is:

$ craft controller DashboardController

When we run this command we now have a new class under app/http/controllers/DashboardController called DashboardController. By convention, Masonite expects that all controllers have their own file since it’s an extremely easy way to keep track of all your classes since the class name is the same name as the file but you can obviously name this class wherever you like.

Defining a Controller Method

Controller methods are very similar to function based views in a Django application except this is just a normal class method. Our controller methods at a minimum should look like:

def show(self):
    pass

All controller methods must have the self parameter. The self parameter is the normal python self object which is just an instance of the current class as usual. Nothing special here.

All controller methods are resolved by the container so you may also retrieve additional objects from the container by specifying them as a parameter:

def show(self, Request):
    print(Request) # Grabbed the Request object from the container

It’s important to note that unlike other frameworks, we do not have to specify our route parameters as parameters in our controller method. We can retrieve the parameters using the Request.param('key') class method.

This might look magical to you so be sure the read about the IOC container in the documentation.

Service Container

The Craft Command

The Craft Command

Introduction

The craft command tool is a powerful developer tool that lets you quickly scaffold your project with models, controllers and views as well as condense nearly everything down to it’s simplest form via the craft namespace.

For example, In Django you may need to do something like:

$ django-admin startproject
$ python manage.py runserver
$ python manage.py migrate

The craft tool condenses all commonly used commands into its own namespace

$ craft new
$ craft serve
$ craft migrate

All scaffolding of Masonite can be done manually (manually creating a controller and importing the view function for example) but the craft command tool is used for speeding up development and cutting down on mundane development time.

Commands

The possible commands for craft include:

Creating an Authentication System

To create an authentication system with a login, register and a dashboard system, just run:

 $ craft auth

This command will create several new templates, controllers and routes so you don’t need to create an authentication system from scratch, although you can. If you need a custom authentication system, this command will scaffold the project for you so you can go into these new controllers and change them how you see fit.

These new controllers are not apart of the framework itself but now apart of your project. Do not look at editing these controllers as editing the framework source code.

Creating Controllers

If you wish to scaffold a controller, just run:

$ craft controller

This command will create a new controller under app/http/controller. By convention, all controllers should have an appended “Controller”. For example in order to make a dashboard controller, you should run craft controller DashboardController and not craft controller Dashboard although you can name your controllers however you like.

Creating a New Project

If you’d like to start a new project, you can run:

$ craft new project_name

This will download a zip file of the MasoniteFramework/masonite repository and unzip it into your current working directory. This command will default to the latest release of the repo.

You may also specify some options. The --version option will create a new project depending on the releases from the MasoniteFramework/masonite repository.

$ craft new project_name --version 1.3.0

Or you can specify the branch you would like to create a new project with:

$ craft new project_name --branch develop

After you have created a new project, you will have a requirements.txt file with all of the projects dependencies. In addition to this file, you will also have a .env-example file which contains a boiler plate of a .env file. In order to install the dependencies, as well as copy the example environment file to a .env file, just run:

$ craft install

The craft install command will also run craft key --store as well which generates a secret key and places it in the .env file.

Creating Migrations

All frameworks have a way to create migrations in order to manipulate database tables. Masonite uses a little bit of a different approach to migrations than other Python frameworks and makes the developer edit the migration file. This is the command to make a migration for an existing table:

$ craft migration name_of_migration —-table users

If you are creating a migration for a table that does not exist yet which the migration will create it, you can pass the --create flag like so:

$ craft migration name_of_migration --create users

These two flags will create slightly different types of migrations.

Migrating

After your migrations have been created, edited, and are ready for migrating, we can now migrate them into the database. To migrate all of your unmigrated migrations, just run:

$ craft migrate

You can also refresh and rollback all of your migrations and remigrate them. This will basically rebuild your entire database.

$ craft migrate:refresh

You can also rollback all migrations without remigrating

$ craft migrate:reset

Lastly, you can rollback just the last set of migrations you tried migrating

$ craft migrate:rollback

Models

If you'd like to create a model, you can run:

$ craft model ModelName

This will scaffold a model under app/ModelName and import everything needed.

If you need to create a model in a specific folder starting from the app folder, then just run:

$ craft model Models/ModelName

This will create a model in app/Models/ModelName.py.

Creating a Service Provider

Service Providers are a really powerful feature of Masonite. If you'd like to create your own service provider, just run:

$ craft provider DashboardProvider

This will create a file at app/providers/DashboardProvider.py

Creating a Job

Jobs are used for Masonite's queue systems. You can create these Queueable classes and they will be able to be loaded into different queues. To create a job, run:

$ craft job JobName

This will create a job inside the app/jobs directory.

Creating Views

Views are simply html files located in resources/templates and can be created easily from running the command:

$ craft view blog

This command will create a template at resources/templates/blog.html

You can also create a view deeper inside the resources/templates directory.

$ craft view auth/home

This will create a view under resources/templates/auth/home.html but keep in mind that it will not create the directory for you. If the auth directory does not exist, this command will fail.

Creating Jobs

Jobs are designed to be loaded into queues. We can take time consuming tasks and throw them inside of a Job. We can then use this Job to push to a queue to speed up the performance of our application and prevent bottlenecks and slowdowns.

$ craft job SendWelcomeEmail

Packages

$ craft package name_of_package

Publishing

$ craft publish name_of_package

Running the WSGI Server

You can run the WSGI server by simply running:

$ craft serve

Encryption

To generate a secret key, we can run:

$ craft key

This will generate a 32 bit string which you can paste into your .env file under the KEY setting.

You may also pass the --store flag which will automatically add the key to your .env file:

$ craft key --store

This command is ran whenever you run craft install

Great! You are now a master at the craft command line tool.

Read more about Service Providers under the documentation.

Jobs will be put inside the app/jobs directory. See the documentation for more information.

You may create a PyPi package with an added integrations.py file which is specific to Masonite. You can learn more about packages by reading the documentation. To create a package boilerplate, just run:

Packages that are built specifically for Masonite in mind will typically support publishing commands. Publishing commands are a way that packages can scaffold and integrate into Masonite. Publishing commands can allow third parties to: create or append to configuration files, create controllers, create routes and other integrations. Read more about publishing by reading our documentation. To publish a package just run:

Masonite comes with a way to encrypt data and by default, encrypts all cookies set by the framework. Masonite uses a key to encrypt and decrypt data. Read the documentation for more information on encryption.

Service Provider
Queues and Jobs
Creating Packages
Publishing Packages
Encryption

Views

Views

Introduction

Views contain all the HTML that you’re application will use to render to the user. Unlike Django, views in Masonite are your HTML templates. All views are located inside resources/templates

All views are rendered with Jinja2 so can use all the Jinja2 code you are used to. An example view looks like:

<!-- View stored in resources/templates/helloworld.html -->

<html>
  <body>
    <h1> Hello {{ 'world' }}</h1>
  </body>
</html>

Creating Views

Since all views are located in resources/templates, we can use simply create all of our views manually here or use our craft command tool. To make a view just run:

$ craft view hello

This will create a template under resources/templates/hello.html.

Calling Views

Helper Function

One of the helper functions is the view() function which is accessible like any other built in Python function.

We can call views in our controllers like so:

def show(self):
    return view('dashboard')

This will return the view located at resources/templates/dashboard.html. We can also specify a deeper folder structure like so:

def show(self):
    return view('profiles/dashboard')

This will look for the view at resources/templates/profiles/dashboard.html

From The Container

The View class is loaded into the container so we can retrieve it in our controller methods like so:

def show(self, View):
    return View('dashboard')

This is exactly the same as using the helper function above. So if you choose to code more explicitly, the option is there for you.

Passing Data to Views

A lot of the time we’ll need to pass in data to our views. This data is passed in with a dictionary that contains a key which is the variable with the corresponding value. We can pass data to the function like so:

def show(self, Request):
    return view('dashboard', {'id': Request.param('id')})

This will send a variable named id to the view which can then be rendered like:

<!-- View stored in resources/templates/dashboard -->

<html>
  <body>
    <h1> {{ id }} </h1>
  </body>
</html>

Requests

Requests

Introduction

Getting Started

The Request class is bound into the IOC container once when the server is first started. This takes the WSGI environment variables generated by your WSGI server as a parameter. Because of this, we reload the WSGI values on every request. This is done already for you by Masonite. This Request class is bound and initialized inside the AppProvider Service Provider. We grab this request object by simply passing in Request into the parameters of anything resolved by the Service Container such as middleware, drivers and controller methods like so:

Masonite is smart enough to know that we need the Request class and it will inject it into our method for us.

Helper Function

Masonite ships with a HelpersProvider Service Provider which adds several helper functions. One of these helper functions is the request() function. This function will return the request object. Because of this, these two pieces of code are identical:

Usage

The Request has several helper methods attached to it in order to interact with various aspects of the request.

In order to get the current request input variables such as the form data during a POST request or the query string during a GET request looks like:

NOTE: There is no difference between GET and POST when it comes to getting input data. They are both retrieved through this .input() method so there is no need to make a distinction if the request is GET or POST

Method Options

We can get all the request input variables such as input data from a POST form request or GET data from a query string. This will return all the available request input variables for that request as a dictionary.

To check if some request input data exists:

To get the request parameter retrieved from the url. This is used to get variables inside: /dashboard/@firstname for example.

You may also set a cookie in the browser. The below code will set a cookie named key to the value of value. By default, all cookies are encrypted with your secret key which is generated in your .env file when you installed Masonite.

If you choose to not encrypt your values and create cookies with the plain text value then you can pass a third value of True or False. You can also be more explicit if you like:

You can get all the cookies set from the browser

You can get a specific cookie set from the browser

Again, all cookies are encrypted by default so if you set a cookie with encryption then this method will decrypt the cookie. If you set a cookie in plain text then you should pass the False as the second parameter here to tell Masonite not to decrypt your plain text cookie value. If you do not do this then Masonite will throw an invalid token exception:

This will return the plain text version of the cookie.

You can also get the current user from the request. This requires the LoadUserMiddleware middleware which is in Masonite by default. This will return an instance of the current user.

You can specify a url to redirect to

If the url contains http than the route will redirect to the external website

You can redirect to a named route

You can also go back to a named route specified from the form input back. This will get the request input named back and redirect to that named route. This is great if you want to redirect the user to a login page and then back to where they came from. Just remember during your form submission that you need to supply a back input.

This is equivalent to:

You can also specify the input parameter that contains the named route

Sometimes your routes may require parameters passed to it such as redirecting to a route that has a url like: /url/@firstname:string/@lastname:string. For this you can use the send method. Currently this only works with named routes.

You can load a specific secret key into the request by using:

This will load a secret key into the request which will be used for encryptions purposes throughout your Masonite project. Note that by default, the secret key is pulled from your configuration file so you do NOT need to supply a secret key, but the option is there if you need to change it

There are several ways we can call views in our controllers. The first recommended way is using the view() function. Masonite ships with a HelpersProvider Service Provider. This provider will add several new built in functions to your project. These helper functions can be used as shorthand for several commonly used classes such as the View and Request class. See the documentation for more information.

Remember that by passing in parameters like Request to the controller method, we can retrieve objects from the IOC container. Read more about the IOC container in the documentation.

The Request class is initialized when the server first starts and changes based on every request by the framework. The Request class is loaded into the IOC container so any Service Provider will have access to it. The IOC container allows all parts of the framework to be resolved by the IOC container and auto inject any dependencies they need. Read more about the IOC container in the documentation.

Notice we didn't import anything at the top of our file and also didn't retrieve any objects from the IOC container. Masonite helper functions act just like any other built in Python function. Read more about helper functions in the documentation.

Helper Functions
Service Container
def show(self, Request):
    # Request is the instance of the Request class
    pass
def show(self, Request):
    Request.input('username')
def show(self):
    request().input('username')
def show(self, Request):
    Request.input('username')
def show(self, Request):
    return Request.all()
def show(self, Request):
    return Request.has('variable')
def show(self, Request):
    return Request.param('firstname')
def show(self, Request):
    return request.cookie('key', 'value')
def show(self, Request):
    return request.cookie('key', 'value', encrypt=False)
def show(self, Request):
    return request.get_cookies()
def show(self, Request):
    return Request.get_cookie('key')
def show(self, Request):
    return Request.get_cookie('key', decrypt=False)
def show(self, Request):
    return Request.user()
def show(self, Request):
    return Request.redirect('/home')
def show(self, Request):
    return Request.redirect('http://google.com')
def show(self, Request):
    return Request.redirectTo('dashboard')
def show(self, Request):
    return Request.back()
def show(self, Request):
    return Request.redirectTo(request.input('back'))
def show(self, Request):
    return Request.back('redirect')
def show(self, Request):
    return Request.back().send({'firstname': 'Joseph', 'lastname': 'Mancuso'})

    return Request.redirectTo('dashboard').send({'firstname': 'Joseph', 'lastname': 'Mancuso'})
Request.key(key)
Service Container
Helper Functions

Static Files

Static Files

Introduction

Masonite tries to make static files extremely easy and comes with whitenoise out of the box. White noise wraps the WSGI application and listens for certain URI requests that can be resistered in your configuration files.

Configuration

All configurations that are specific to static files can be found in config/storage.py. In this file you'll find a constant file called STATICFILES which is simply a dictionary of directories as they keys and aliases as the value.

The directories to include as keys is simply the location of your static file locations. For example, if your css files are in storage/assets/css then put that folder location as the key. For the value, put the alias you want to use in your templates. For this example, we will use css/ as the alias.

For this setup, our STATICFILES constant should look like:

STATICFILES = {
    'storage/assets/css': 'css/',
}

Now in our templates we can use:

<img src="/css/style.css">

Which will get the storage/assets/css/style.css file.

Thats it! Static files are extremely simple. You are now a master at static files!

Helper Functions

Helper Functions

Introduction

Masonite works on getting rid of all those mundane tasks that developers either dread writing or dread writing over and over again. Because of this, Masonite has several helper functions that allows you to quickly write the code you want to write without worrying about imports or retrieving things from the Service Container. Many things inside the Service Container are simply retrieved using several functions that Masonite sets as builtin functions.

These functions do not require any imports and are simply just available which is similiar to the print() function. These functions are all set inside the HelpersProvider Service Provider.

It may make more sense if we take a peak at this Service Provider:

class HelpersProvider(ServiceProvider):

    wsgi = False

    def register(self):
        pass

    def boot(self, View, ViewClass, Request):
        ''' Add helper functions to Masonite '''
        builtins.view = View
        builtins.request = Request.helper
        builtins.auth = Request.user
        builtins.container = self.app.helper
        builtins.env = os.getenv
        builtins.resolve = self.app.resolve

        ViewClass.share({'request': Request.helper, 'auth': Request.user})

Notice how we simply just add builtin functions via this provider.

Request

The Request class has a simple request() helper function.

def show(self):
    request().input('id')

is exactly the same as:

def show(self, Request):
    Request.input('id')

View

The view() function is just a shortcut to the View class.

def show(self):
    return view('template_name')

is exactly the same as:

def show(self, View):
    return View('template_name')

Auth

The auth() function is a shortcut around getting the current user. We can retrieve the user like so:

def show(self):
    auth().id

is exactly the same as:

def show(self, Request):
    Request.user().id

This will return None if there is no user.

Container

We can get the container by using the container() function

def show(self):
    container().make('User')

is exactly the same as:

def show(self, Request):
    Request.app().make('User')

Env

We may need to get some environment variables inside our controller or other parts of our application. For this we can use the env() function.

def show(self):
    env('S3_SECRET')

is exactly the same as:

import os

def show(self):
    os.environ.get('S3_SECRET')

Resolve

We can resolve anything from the container by using his resolve() function.

def some_function(Request):
    print(Request)

def show(self):
    resolve(some_function)

is exactly the same as:

def some_function(Request):
    print(Request)

def show(self, Request):
    Request.app().resolve(some_function)

That's it! These are simply just functions that are added to Python's builtin functions.

Introduction

The Craft Command

Introduction

The craft command tool is a powerful developer tool that lets you quickly scaffold your project with models, controllers, views, commands, providers, etc. which will condense nearly everything down to it’s simplest form via the craft namespace. No more redundancy in your development time creating boilerplate code. Masonite condenses all common development tasks into a single namespace.

For example, In Django you may need to do something like:

$ django-admin startproject
$ python manage.py runserver
$ python manage.py migrate

The craft tool condenses all commonly used commands into its own namespace

$ craft new
$ craft serve
$ craft migrate

All scaffolding of Masonite can be done manually (manually creating a controller and importing the view function for example) but the craft command tool is used for speeding up development and cutting down on mundane development time.

Commands

The possible commands for craft include:

Creating an Authentication System

To create an authentication system with a login, register and a dashboard system, just run:

 $ craft auth

This command will create several new templates, controllers and routes so you don’t need to create an authentication system from scratch, although you can. If you need a custom authentication system, this command will scaffold the project for you so you can go into these new controllers and change them how you see fit.

These new controllers are not apart of the framework itself but now apart of your project. Do not look at editing these controllers as editing the framework source code.

Creating Controllers

If you wish to scaffold a controller, just run:

$ craft controller

This command will create a new controller under app/http/controller. By convention, all controllers should have an appended “Controller”. For example in order to make a dashboard controller, you should run craft controller DashboardController and not craft controller Dashboard although you can name your controllers however you like.

Creating a New Project

If you’d like to start a new project, you can run:

$ craft new project_name

This will download a zip file of the MasoniteFramework/masonite repository and unzip it into your current working directory. This command will default to the latest release of the repo.

You may also specify some options. The --version option will create a new project depending on the releases from the MasoniteFramework/masonite repository.

$ craft new project_name --version 1.3.0

Or you can specify the branch you would like to create a new project with:

$ craft new project_name --branch develop

After you have created a new project, you will have a requirements.txt file with all of the projects dependencies. In addition to this file, you will also have a .env-example file which contains a boiler plate of a .env file. In order to install the dependencies, as well as copy the example environment file to a .env file, just run:

$ craft install

The craft install command will also run craft key --store as well which generates a secret key and places it in the .env file.

Creating Migrations

All frameworks have a way to create migrations in order to manipulate database tables. Masonite uses a little bit of a different approach to migrations than other Python frameworks and makes the developer edit the migration file. This is the command to make a migration for an existing table:

$ craft migration name_of_migration —-table users

If you are creating a migration for a table that does not exist yet which the migration will create it, you can pass the --create flag like so:

$ craft migration name_of_migration --create users

These two flags will create slightly different types of migrations.

Migrating

After your migrations have been created, edited, and are ready for migrating, we can now migrate them into the database. To migrate all of your unmigrated migrations, just run:

$ craft migrate

You can also refresh and rollback all of your migrations and remigrate them. This will basically rebuild your entire database.

$ craft migrate:refresh

You can also rollback all migrations without remigrating

$ craft migrate:reset

Lastly, you can rollback just the last set of migrations you tried migrating

$ craft migrate:rollback

Models

If you'd like to create a model, you can run:

$ craft model ModelName

This will scaffold a model under app/ModelName and import everything needed.

If you need to create a model in a specific folder starting from the app folder, then just run:

$ craft model Models/ModelName

This will create a model in app/Models/ModelName.py.

Creating a Service Provider

Service Providers are a really powerful feature of Masonite. If you'd like to create your own service provider, just run:

$ craft provider DashboardProvider

This will create a file at app/providers/DashboardProvider.py

Creating a Job

Jobs are used for Masonite's queue systems. You can create these Queueable classes and they will be able to be loaded into different queues. To create a job, run:

$ craft job JobName

This will create a job inside the app/jobs directory.

Creating Views

Views are simply html files located in resources/templates and can be created easily from running the command:

$ craft view blog

This command will create a template at resources/templates/blog.html

You can also create a view deeper inside the resources/templates directory.

$ craft view auth/home

This will create a view under resources/templates/auth/home.html but keep in mind that it will not create the directory for you. If the auth directory does not exist, this command will fail.

Creating Jobs

Jobs are designed to be loaded into queues. We can take time consuming tasks and throw them inside of a Job. We can then use this Job to push to a queue to speed up the performance of our application and prevent bottlenecks and slowdowns.

$ craft job SendWelcomeEmail

Packages

$ craft package name_of_package

Publishing

$ craft publish name_of_package

Running the WSGI Server

You can run the WSGI server by simply running:

$ craft serve

Encryption

To generate a secret key, we can run:

$ craft key

This will generate a 32 bit string which you can paste into your .env file under the KEY setting.

You may also pass the --store flag which will automatically add the key to your .env file:

$ craft key --store

This command is ran whenever you run craft install

Great! You are now a master at the craft command line tool.

Read more about Service Providers under the documentation.

Jobs will be put inside the app/jobs directory. See the documentation for more information.

You may create a PyPi package with an added integrations.py file which is specific to Masonite. You can learn more about packages by reading the documentation. To create a package boilerplate, just run:

Packages that are built specifically for Masonite in mind will typically support publishing commands. Publishing commands are a way that packages can scaffold and integrate into Masonite. Publishing commands can allow third parties to: create or append to configuration files, create controllers, create routes and other integrations. Read more about publishing by reading our documentation. To publish a package just run:

Masonite comes with a way to encrypt data and by default, encrypts all cookies set by the framework. Masonite uses a key to encrypt and decrypt data. Read the documentation for more information on encryption.

Service Provider
Queues and Jobs
Creating Packages
Publishing Packages
Encryption

Creating Commands

Creating Commands

Introduction

It's extremely simple to add commands to Masonite via the craft command tool and Service Providers. If you have been using Masonite for any amount of time you will learn that commands are a huge part of developing web applications with Masonite. We have made it extremely easy to create these commands and add them to craft to build really fast personal commands that you might use often.

Getting Started

You can create commands by using craft itself:

$ craft command HelloWorldCommand

This will create a app/commands/HelloWorldCommand.py file with boiler plate code that looks like this:

""" A HelloWorldCommand Command """
from cleo import Command


class HelloWorldCommand(Command):
    """
    Description of command

    command:name
        {argument : description}
    """

    def handle(self):
        pass

Let's create a simple hello world application which prints "hello world" to the console. Inside the handle method we can simply put:

...

def handle(self):
    print('Hello World')

That's it! Now we just have to add it to our craft command.

Adding Our Command To Craft

Authentication System

Request Lifecycle

Request Lifecycle

Introduction

Lifecycle Overview

First Things

Initialization

Requests in Middleware

If one of the middleware has instructed the request object to redirect, the view that is ready to execute, will not execute.

For example, if the user is planned on going to the dashboard view, but middleware has told the request to redirect to the login page instead then the dashboard view, and therefore the controller, will not execute at all. It will be skipped over. Masonite checks if the request is redirecting before executing a view.

Also, the request object can be injected into middleware by passing the Request parameter into the constructor like so:

class SomeMiddleware:

    def __init__(self, Request):
        self.request = Request

    ...

Requests in the API

Masonite comes with a built in API system for testing and personal development. It is not yet ready for production and lacks several authentication features.

The request object that is loaded in the API class will check the base URI and then execute CRUD operations based on the URI. As a developer, you are not responsible for manipulating the request object in your API classes.

Requests and Redirecting

If the user is redirecting to a normal URL, it will not check any routes. The request will then send a 302 response and redirect the user to the route specified.

Not Redirecting

If the request is not redirecting, then it will return a 200 status code response and simply show the output needed. This output will come from the controller.

Finally, the data returned from the controller is then passed into the return statement so the WSGI server can interpret it.

It's important to know the life cycle of the request so you can understand what is going on under the hood in order to write better software. Whenever you have a better understanding of how your development tools work, you will feel more confident as you'll understand what exactly is going on. This documentation will try to explain in as much detail as needed the flow of the request from initiation to execution. To read about how to use the Request class, read the documentation.

All of Masonite is bootstrapped via and is centralized via a . The Request class in binded into the container inside the AppProvider Service Provider which is inside the Masonite pip package. The Request class is initialized and registered into the container before the WSGI server starts. Because of this, the Request class is the same instance throughout the life of the server. In other words, the Request class is a singleton for the life of the WSGI server and is not re-instantiated on each request. On each request, the WSGI server will load the environ variable (the WSGI request details) into the request class which changes the behavior of requests accordingly such as what the URI is or what the request method type is.

The request object is initialized in the AppProvider Service Provider and simply takes the environ variable as a dependency which is passed with all WSGI servers and hold information about the: request, server, URI, request method etc. The request object will then parse the environ and store them into certain class attributes. The request object has several methods that assist in extracting these attributes into usable and memorable methods. Read more about how to use the request object in the documentation.

This will inject the Request class into the constructor when that middleware is executed. Read more about how middleware works in the documentation.

Towards the end of the request lifecycle, Masonite will check if Masonite should redirect the user. This happens whenever the redirecting methods are exectuted on the request object. If the user wants to redirect to a named route, Masonite will loop through all the routes inside routes/web.py and check all the route names. If a name matches, it will execute that route. If the route requires parameters (such that a route has a @variable in the route URI) then you will need to pass the .send() method when redirecting. More about request redirecting in the documentation.

Requests
Service Providers
Service Container
Requests
Middleware
Requests

Service Providers

Service Providers

Introduction

You may create your own service provider and add it to your providers list to extend Masonite, or even remove some providers if you don't need their functionality. If you do create your own Service Provider, consider making it available on PyPi so others can install it into their framework.

Creating a Provider

We can create a Service Provider but simply using a craft command:

$ craft provider DashboardProvider

This will create a new Service Provider under our app/providers/DashboardProvider.py. This new Service Provider will have two simple methods, a register method and a boot method. We'll explain both in detail.

Service Provider Execution

There are a few architectural examples we will walk through to get you familiar with how Service Providers work under the hood. Let's look at a simple provider and walk through it.

from masonite.provider import ServiceProvider
from app.User import User

class UserModelProvider(ServiceProvider):
    ''' Binds the User model into the Service Container '''

    wsgi = False 

    def register(self):
        self.app.bind('User', User)

    def boot(self):
        print(self.app.make('User'))

We can see that we have a simple provider that registers the User model into the container. There are three key features we have to go into detail here.

WSGI

First, the wsgi = False just tells Masonite that this specific provider does not need the WSGI server to be running. When the WSGI server first starts, it will execute all service providers that have wsgi set to False. Whenever a provider only binds things into the container and we don't need things like requests or routes, then consider setting wsgi to False. the ServiceProvider class we inherited from sets wsgi to True by default. Whenever wsgi is True then the service provider will fire on every request.

Register

In our register method, it's important that we only bind things into the container. When the server is booted, Masonite will execute all register methods on all service providers. This is so the boot method will have access to the entire container.

Boot

The boot method will have access to everything that is registered in the container and is actually resolved by the container. Because of this, we can actually rewrite our provider above as this:

from masonite.provider import ServiceProvider
from app.User import User

class UserModelProvider(ServiceProvider):
    ''' Binds the User model into the Service Container '''

    wsgi = False 

    def register(self):
        self.app.bind('User', User)

    def boot(self, User):
        print(User)

This will be exactly the same as above. Notice that the boot method is resolved by the container.

Great! It's really that simple. Just this knowledge will take you a long way. Take a look at the other service providers to get some inspiration on how you should create yours. Again, if you do create a Service Provider, consider making it available on PyPi so others can install it into their framework.

Service Providers are the key building blocks to Masonite. The only thing they do is register things into the Service Container, or retrieve things from the Service Container. You can read more about the Service Container in the documentation. If you look inside the config/application.py file, you will find a PROVIDERS list which contains all the Service Providers involved in building the framework.

Service Container

Service Container

Service Container

Introduction

The Service Container is an extremely powerful feature of Masonite and should be used to the fullest extent possible. It's important to understand the concepts of the Service Container. It's a simple concept but is a bit magical if you don't understand what's going on under the hood.

Getting Started

The Service Container is just a dictionary where classes are loaded into it by key-value pairs, and then can be retrieved by either the key or value. That's it.

The container is contained inside the App class which is instantiated in the beginning of the framework and passed through various parts of the project such as controllers, middleware and drivers.

There are four methods that are important in interacting with the container: bind, make and resolve

Bind

In order to bind classes into the container, we will just need to use a simple bind method on our app container. In a service provider, that will look like:

from masonite.provider import ServiceProvider
from app.User import User
from masonite.request import Request

class UserModelProvider(ServiceProvider):

    def register(self):
        self.app.bind('User', User)

    def boot(self):
        pass

This will load the key value pair in the providers dictionary in the container. The dictionary after this call will look like:

>>> app.providers
{'User': <class masonite.User.User>}

The service container is available in the Request object and can be retrieved by:

def show(self, Request):
    Request.app() # will return the service container

Make

In order to retrieve a class from the service container, we can simply use the make method.

>>> from app.User import User
>>> app.bind('User', User)
>>> app.make('User')
<class app.User.User>

That's it! This is useful as an IOC container which you can load a single class into the container and use that class everywhere throughout your project.

Resolve

This is the most useful part of the container. It is possible to retrieve objects from the container by simply passing them into the parameters. Certain aspects of Masonite are resolved such as controller methods, middleware and drivers.

For example, we can hint that we want to get the Request class and put it into our controller. All controller methods are resolved by the container.

def show(self, Request)
    Request.user()

In this example, before the show method is called, Masonite will look at the parameters and look inside the container for a key with the same name. In this example we are looking for Request so Masonite will look for a key inside the provider dictionary called Request and inject that value from the container into our method for us. Request is already loaded into the container for you out of the box.

Another way to resolve classes is by using Python 3 annotations:

from masonite.request import Request

def show(self, request_class: Request)
    request_class.user()

Masonite will know that you are trying to get the Request class and will actually retrieve that class from the container. Masonite will search the container for a Request class regardless of what the key is in the container, retrieve it, and inject it into the controller method. Effectively creating an IOC container with dependency injection. Think of this as a get by value instead of a get by key like the earlier example.

Pretty powerful stuff, eh?

Resolving your own code

The service container can also be used outside of the flow of Masonite. Masonite takes in a function or class method, and resolves it's dependencies by finding them in the service container and injecting them for you.

Because of this, you can resolve any of your own classes or functions.

from masonite.request import Request

def randomFunction(User):
    print(User)

def show(self, Request):
    Request.app().resolve(randomFunction) # Will print the User object

Remember not to call it and only reference the function. The Service Container needs to inject dependencies into the object so it requires a reference and not a callable.

This will fetch all of the parameters of randomFunction and retrieve them from the service container. There probably won't be many times you'll have to resolve your own code but the option is there.

Publishing Packages

Publishing Packages

Introduction

NOTE: Virtual Environment

If you are in a virtual environment,craft publishwill not have access to your virtual environment dependencies. In order to fix this, we can add our site packages to ourconfig/packages.pyconfig file

If you attempt to publish your package without your virtual environment's site_packages file being inside config/packages.py, you will encounter a ModuleNotFound error that says it cannot find the integrations file located with the package you are trying to install. This is because Masonite does not have knowledge of your virtual environments dependencies, only your system dependencies.

If you are in a virtual environment then go to yourconfig/packages.pyfile and add your virtual environments site_packages folder to theSITE_PACKAGESlist. YourSITE_PACKAGESlist may look something like:

SITE_PACKAGES = [
    'venv/lib/python3.6/site-packages'
]

Once done, all future packages that you pip install will be available through the publish command. This configuration should be done as soon as your virtual environment is created so you don't encounter any errors while trying to publish packages.

Publishing packages are a great way for third party packages to integrate into Masonite. They are extremely easy to setup even on existing pip packages. Publishing packages allows any package to create configuration files, routes, controllers, and other integrations that make developing with your packages amazing. You can read about this in the documentation to learn more about how you can integrate your existing packages or future packages with Masonite.

This will allowcraft publishto find our dependencies installed on our virtual environment. Read the documentation for more information.

Creating Packages
Publishing Packages

Creating Commands

Creating Commands

Introduction

Creating a command is quite simple with Masonite and allows other developers to use your package in the command line similiar to a craft command by running craft-vendor. In this documentation we'll talk about how to create a package that can expand the craft tool by using craft-vendor which comes with the masonite-cli pip package.

Virtual Environments

It's important to note that craft-vendor does not have access to your virtual environment by default, only your system packages. What we can do is add our virtual environment's site_packages directory to our config/packages.py config file which should look something like:

SITE_PACKAGES = [
    'venv/lib/python3.6/site-packages'
]

This will take those paths and temporarily add it to the sys.path for the duration of the craft-vendor command.

Getting Started

The craft command comes with a package helper and can be used to create the boilerplate for Masonite packages. We can use this boilerplate to quickly create a package that can be used on the masonite command line. Lets create our boiler plate now by navigating to a directory we would like to build our package in and run:

$ craft package testpackage

This will create a file structure like:

testpackage/
    __init__.py
    integration.py
MANIFEST.in
setup.py

You can ignore the integration file for now as we won't be using it in this tutorial. This integration file is used to scaffold other Masonite projects (like adding configuration files, controllers, routes etc.)

Commands module

All Masonite packages that would like users to interact with their package via the command line will need a commands module. Let's create one now and make our package structure look like:

testpackage/
    __init__.py
    integration.py
    commands/
        __init__.py
        testpackage.py
MANIFEST.in
setup.py

Craft Vendor Commands

The craft-vendor command is separate from our normal craft command but is primarily for running third party package commands. This is apart of the masonite-cli package.

How the craft-vendor command works is there are three possible commands that can be ran after someone installs your package:

$ craft-vendor testpackage
$ craft-vendor testpackage submodule
$ craft-vendor testpackage submodule function_name

Running craft-vendor testpackage

This allows for some flexibility in how your commands can be ran. Lets start by explaining how the first command will interact with your package.

$ craft-vendor testpackage

When the user runs this command, craft-vendor will look for a package called testpackage. Once it is found, it will look into the commands module and look for a file called testpackage, and then a function in that file called testpackage and execute that function. In this instance, we might have a structure like:

testpackage/
    __init__.py
    integration.py
    commands/
        __init__.py
        testpackage.py
MANIFEST.in
setup.py

and then inside testpackage/commands/testpackage will look like:

def testpackage():
    print('you have just ran the craft-vendor testpackage command')

Running craft-vendor testpackage payment

When the user runs this command, it will find the package called testpackage, look inside the commands module and for a file called payments.py and execute a function called payments. In this instance, we might have a structure like:

testpackage/
    __init__.py
    integration.py
    commands/
        __init__.py
        testpackage.py
        payments.py
MANIFEST.in
setup.py

and then inside testpackage/commands/payments.py will look like:

def payments():
    print('you have just ran the craft-vendor testpackage payments command')

Running craft-vendor testpackage payment stripe

Lastly, When the user runs this command, it will find the package called testpackage, look inside the commands module and for a file called payments.py and execute a function called stripe. In this instance, we might have a structure like:

testpackage/
    __init__.py
    integration.py
    commands/
        __init__.py
        testpackage.py
        payments.py
MANIFEST.in
setup.py

and then inside testpackage/commands/payments.py will look like:

def stripe():
    print('you have just ran the craft-vendor testpackage payments stripe command')

Uploading to PyPi

To upload to PyPi we just have to think of an awesome name for our package and put it in the setup.py file. Now that you have a super awesome name, we'll just need to run:

$ python setup.py sdist upload

which should upload your package with your credentials from your .pypirc file. Make sure you click the link above and see how to make one.

Working With Our Package

We can either test our package locally or upload our package to PyPi.

To test our package locally, if you use virtual environments, just go to your Masonite project and activate your virtual environment. Navigate to the folder where you created your package via the command line and run:

$ pip install .

If you want to be able to make changes without having to constantly reinstall your package then run

$ pip install --editable .

This will install your new package into your virtual environment. Go back to your project root so we can run our craft-vendor command. If we run craft-vendor testpackage we should see the respective print message. Try running all three commands and see the different print output. If you are getting an error of ModuleNotFound and you are inside a virtual environment, don't forget to add the site_packages directory to your config/packages.py by following the instructions at the top of this documentation.

If you have never set up a package before then you'll need to . This file will hold our PyPi credentials.

check how to make a .pypirc file

Middleware

Middleware

Introduction

Middleware is an extremely important aspect of web applications as it allows you to run important code either before or after every request or even before or after certain routes. In this documentation we'll talk about how middleware works, how to consume middleware and how to create your own middleware. Middleware is only ran when the route is found and a status code of 200 will be returned.

Getting Started

Middleware classes are placed inside the app/http/middleware by convention but can be placed anywhere you like. All middleware are just classes that contain a before method and/or an after method.

There are four types of middleware in total:

  • Middleware ran before every request

  • Middleware ran after every request

  • Middleware ran before certain routes

  • Middleware ran after certain routes

Creating Middleware

Again, middleware should live inside the app/http/middleware folder and should look something like:

class AuthenticationMiddleware:
    ''' Middleware class '''

    def __init__(self, Request):
        self.request = Request

    def before(self):
        pass

    def after(self):
        pass

If Masonite is running a “before” middleware, that is middleware that should be ran before the request, Masonite will check all middleware and look for a before method and execute that. The same for “after” middleware.

You may exclude either method if you do not wish for that middleware to run before or after.

This is a boilerplate for middleware. It's simply a class with a before and/or after method. Creating a middleware is that simple. Let's create a middleware that checks if the user is authenticated and redirect to the login page if they are not. Because we have access to the request object from the Service Container, we can do something like:

class AuthenticationMiddleware:
    ''' Middleware class which loads the current user into the request '''

    def __init__(self, Request):
        self.request = Request

    def before(self):
        if not self.request.user():
            self.request.redirectTo('login')

    def after(self):
        pass

That's it! Now we just have to make sure our route picks this up. If we wanted this to execute after a request, we could use the exact same logic in the after method instead.

Since we are not utilizing the after method, we may exclude it all together. Masonite will check if the method exists before executing it.

Configuration

We have one of two configuration constants we need to work with. These constants both reside in our config/middleware.py file and are HTTP_MIDDLEWARE and ROUTE_MIDDLEWARE.

HTTP_MIDDLEWARE is a simple list which should contain an aggregation of your middleware classes. This constant is a list because all middleware will simply run in succession one after another, similar to Django middleware

Middleware is a string to the module location of your middleware class. If your class is located in app/http/middleware/DashboardMiddleware.py then the value we place in our middleware configuration will be a string: app.http.middleware.DashboardMiddleware.DashboardMiddleware. Masonite will locate the class and execute either the before method or the after method.

In our config/middleware.py file this type of middleware may look something like:

HTTP_MIDDLEWARE = [
    'app.http.middleware.DashboardMiddleware.DashboardMiddleware'
]

ROUTE_MIDDLEWARE is also simple but instead of a list, it is a dictionary with a custom name as the key and the middleware class as the value. This is so we can specify the middleware based on the key in our routes file.

In our config/middleware.py file this might look something like:

from app.http.middleware.RouteMiddleware import RouteMiddleware

ROUTE_MIDDLEWARE = {
    'auth': 'app.http.middleware.RouteMiddleware.RouteMiddleware'
}

Consuming Middleware

Using middleware is also simple. If we put our middleware in the HTTP_MIDDLEWARE constant then we don't have to worry about it anymore. It will run on every successful request, that is when a route match is found from our web.py file.

If we are using a route middleware, we'll need to specify which route should execute the middleware. To specify which route we can just append a .middleware() method onto our routes. This will look something like:

Get().route('/dashboard', 'DashboardController@show').name('dashboard').middleware('auth')
Get().route('/login', 'LoginController@show').name('login')

This will execute the auth middleware only when the user visits the /dashboard url and as per our middleware will be redirected to the named route of login

Awesome! You’re now an expert at how middleware works with Masonite.

Middleware constructors are resolved by the container so simply pass in whatever you like in the parameter list and it will be injected for you. Read more about this in the documentation.

Service Container

Creating Packages

Creating a Masonite Package

Introduction

Creating packages is very simple for Masonite. You can get a package created and on PyPi is less than 5 minutes. With Masonite packages you'll easily be able to integrate and scaffold all Masonite projects with ease. Masonite comes with several helper functions in order to create packages that can add configuration files, routes, controllers, views and commands.

Getting Started

As a developer, you will be responsible for both making packages and consuming packages. In this documentation we'll talk about both. We'll start by talking about how to make a package and then talk about how to use that package or other third party packages.

Masonite, being a Python framework, can obviously utilize all Python packages that aren’t designed for a specific framework. For example, Masonite can obviously use a library like requests but can’t use Django Rest Framework.

Similarly to how Django Rest Framework was built for Django, you can also build packages specific to Masonite.

About Packages

There are several key functions that Masonite uses in order to create applications. These include primarily: routes, controllers, views, and craft commands. Creating a package is simple and conveniently Masonite comes with several helper functions in order to create all of these. The developer using your package just needs to run craft publish your-package-name and your package can scaffold out their application for them.

You do not have to use this functionality and instead have the developer copy and paste things that they need but having great setup process is a great way to promote developer happiness.

Creating a Package

Like other parts of Masonite, in order to make a package, we can use a craft command. The craft package command will scaffold out a simple Masonite package and is fully able to be uploaded directly to PyPi.

This should be done in a separate folder outside of your project.

Let's create our package:

$ craft package testpackage

This will create a file structure like:

testpackage/
    __init__.py
    integration.py
MANIFEST.in
setup.py

The integration.py file is important and should not be removed. This is the file that will be used when our users use the craft publish command.

If we open this file we'll notice a single boot() function. Whenever the user (the developer using Masonite) uses the craft publish testpackage command, craft will execute testpackage.integration.boot() so it's wise to load anything you want to be executed on in this function.

You'll notice a helper function imported for you at the top. This create_or_append_config() function does exactly what it says. It will take a config file from your package and put it into the project by either creating it (if it does not exist) or appending it (if it does exist). We'll talk about helper functions later on.

Creating a Config Package

Lets create a simple package that will add or append a config file from our package and into the project.

First lets create a config file inside testpackage/snippets/configs/services.py. We should now have a project structure like:

testpackage/
    __init__.py
    integration.py
    snippets/
        configs/
            services.py
MANIFEST.in
setup.py

Great! inside the services.py lets put a configuration setting:

TESTPACKAGE_PAYMENTS = {
    'stripe': {
        'some key': 'some value',
        'another key': 'another value'
    }
}

Perfect! Now we'll just need to tell PyPi to include this file when we upload it to PyPi. We can do this in our MANIFEST.in file.

include testpackage/snippets/configs/*

Almost done. Now we just need to put our masonite.package helper function in our boot file. The location we put in our create_or_append_config() function should be an absolute path location to our package. To do this, Masonite has put a variable called package_directory inside our integrations.py file. Our boot method should look something like:

def boot():
    create_or_append_config(
        os.path.join(
            package_directory, 'snippets/configs/services.py'
        )
    )

This will append the configuration file that has the same name as our package configuration file. In this case the configuration file we are creating or appending to is config/services.py because our packages configuration file is services.py. If we want to append to another configuration file we can simply change the name of our package configuration file.

Working With Our Package

We can either test our package locally or upload our package to PyPi.

To test our package locally, if you use virtual environments, just go to your Masonite project and activate your virtual environment. Navigate to the folder where you created your package and run:

$ pip install .

If you want to be able to make changes without having to constantly reinstall your package then run

$ pip install --editable .

This will install your new package into your virtual environment. Go back to your project root so we can run our craft publish command. If we run craft publish testpackage we should get a module not found error.

It's important to note that craft publish does not have access to your virtual environment by default, only your system packages. What we can do is add our virtual environments site_packages directory to our config/packages.py config file which should look something like:

SITE_PACKAGES = [
    'venv/lib/python3.6/site-packages'
]

This will take that path and add it to the sys.path for the craft publish script.

Now if we run craft publish we should see that our new configuration file is now in config/services.py file. Awesome! We tried making package support super easy. You of course don't need to integrate directly or scaffold the project but the option is there if you choose to make a package to do so.

Uploading to PyPi

To upload to PyPi we just have to pick a great name for our package in the setup.py file. Now that you have a super awesome name, we'll just need to run:

$ python setup.py sdist upload

which should upload our package with our credentials in our .pypirc file. Make sure you click the link above and see how to make once.

If python doesn’t default to Python 3 or if PyPi throws errors than you may need to run:

$ python3 setup.py sdist upload

Consuming a package.

Now that your package is on PyPi we can just run:

$ pip install super_awesome_package
$ craft publish super_awesome_package

Again, not all packages will need to be published. Only packages that need to scaffold the project. You will know if a package needs to be published by reading the packages install documentation.

Helper Functions

These helper functions are used inside the boot function and are only needed when you need your package to be published.

The location specified as parameters here are absolute path locations. You can achieve this by using the package_directory variable in your integration.py file.

To achieve an absolute path location, this will look like:

location = os.path.join(
            package_directory, 'snippets/configs/services.py'
        )

Functions

All helper functions are located in the masonite.packages module. To use these functions you’ll need to import the function to be used like:

from masonite.packages import create_or_append_config

create_or_append_config(location) will create a configuration file based on a configuration file from your package.

append_web_routes(location) will append web routes to the routes/web.py file. Your web routes should have a += to the ROUTES constant and should look something like:

ROUTES += [
    # your package routes here
]

append_api_routes(location) will append api routes to a masonite project under routes/api.py. Your api routes should have a += to the ROUTES constant and should look something like:

ROUTES += [
    # your package routes here
]

create_controller(location) will take a controller from your package and append it under the app.http.controllers namespace.

If you have never set up a package before then you'll need to . This file will hold our PyPi credentials.

check how to make a .pypirc file

Extending Classes

Extending Classes

Introduction

It's common to want to use a Service Provider to add new methods to a class. For example, you may want to add a is_authenticated method to the Request class. Your package and Service Provider may be for a better authentication system.

You may easily extend classes that inherit from the Extendable class. Many of the built in classes inherit from it.

Usage

You have a few options for adding methods to any of the core classes. You can extend a class with functions, classes and class methods. Typical usage may look like:

def is_authenticated(self):
    return self

def show(self, Request):

    Request.extend(is_authenticated)

    print(Request.is_authenticated()) # returns the Request class

Usage is very simple and has several options for extending a class. Notice that we don't call the function but we pass the reference to it.

Extending a function

This will simply add the function as a bound method to the Request class

def is_authenticated(self):
    return self

def show(self, Request):

    Request.extend(is_authenticated)

    print(Request.is_authenticated()) # returns the Request class

Extending a class method

We can also extend a class method which will take the method given and add it as a bound method.

class Authentication:

    def is_authenticated(self):
        return self

def show(self, Request):

    Request.extend(Authentication.is_authenticated)

    print(Request.is_authenticated()) # returns the Request class

Extending a class

We can even extend a whole class which will get all the classes methods and create bound methods to the Request class.

class Authentication:

    def is_authenticated(self):
        return self

    def login(self):
        return self

def show(self, Request):

    Request.extend(Authentication)

    print(Request.is_authenticated()) # returns the Request class
    print(Request.login()) # returns the Request class

Template Caching

Template Caching

Introduction

Sometimes your templates will not change that often and may have a lot of logic that takes times to run such as several loops or even a very large order of magnitude. If this page is being hit several times per day or even several times per second, you can use template caching in order to put less strain on your server.

This is a powerful feature that will reduce the load of your server for those resource hungry and complex templates.

Getting Started

This feature is introduced in Masonite 1.4 and above. You can check your Masonite version by running pip show masonite which will give you the details of the masonite package you have installed.

All caching configuration is inside config/cache.py which contains two settings, DRIVER and DRIVERS.

We can set the driver we want to use by specifying like so:

DRIVER = 'disk'

Like every other configuration, you'll need to specify the options inside the DRIVERS dictionary:

DRIVERS = {
    'disk': {
        'location': 'bootstrap/cache'
    }
}

All templates cached will be inside that folder. You may wish to specify another directory for your templates such as:

DRIVERS = {
    'disk': {
        'location': 'bootstrap/cache/templates'
    }
}

Caching Templates

In order to cache templates for any given amount of time, you can attach the .cache_for() method onto your view. This looks like:

def show(self):
    return view('dashboard/user').cache_for(5, 'seconds')

This will cache the template for 5 seconds. After 5 seconds, the next hit on that page will show the non cached template and then recache for another 5 seconds.

What has always been annoying in many libraries and frameworks is the distinguishhment between plural and singular such as second and seconds. So if we only want to do 1 minute then that would look like:

def show(self):
    return view('dashboard/user').cache_for(1, 'minute')

Options

There are several cache lengths we can use. Below is all the options for caching:

We can cache for several seconds:

def show(self):
    return view('dashboard/user').cache_for(1, 'second')

def show(self):
    return view('dashboard/user').cache_for(10, 'seconds')

or several minutes:

def show(self):
    return view('dashboard/user').cache_for(1, 'minute')

def show(self):
    return view('dashboard/user').cache_for(10, 'minutes')

or several hours:

def show(self):
    return view('dashboard/user').cache_for(1, 'hour')

def show(self):
    return view('dashboard/user').cache_for(10, 'hours')

or several days:

def show(self):
    return view('dashboard/user').cache_for(1, 'days')

def show(self):
    return view('dashboard/user').cache_for(10, 'days')

or several months:

def show(self):
    return view('dashboard/user').cache_for(1, 'month')

def show(self):
    return view('dashboard/user').cache_for(10, 'months')

or even several years:

def show(self):
    return view('dashboard/user').cache_for(1, 'year')

def show(self):
    return view('dashboard/user').cache_for(10, 'years')

You can use whatever cache you like for caching templates. Only the disk driver is supported out of the box but you can create any drivers you like. Read the documentation on how to create drivers. If you do create a driver, consider making it available on PyPi so others can install it into their projects. If you'd like to contribute to the project and add to the drivers that come freshly installed with Masonite then please visit Masonite's GitHub repository and open an issue for discussing.

About Drivers

Creating a Mail Driver

Creating a Mail Driver

Introduction

Because of Masonite's Service Container, It is extremely easy to make drivers that can be used by simply adding your service provider.

Getting Started

Masonite comes shipped with a Service Provider called MailProvider which loads a few classes into the container as well as boots the default mail driver using the MailManager. This manager class will fetch drivers from the container and instantiate them. We can look at the MailProvider class which will gives us a better explanation as to what's going on:

class MailProvider(ServiceProvider):

    wsgi = False

    def register(self):
        self.app.bind('MailConfig', mail)
        self.app.bind('MailSmtpDriver', MailSmtpDriver)
        self.app.bind('MailMailgunDriver', MailMailgunDriver)

    def boot(self):
        self.app.bind('Mail', MailManager(self.app))

We can see here that because we are only binding things into the container and we don't need the WSGI server to be running, we set wsgi = False. Service Providers that set wsgi to False will only run when the server starts and not on every request.

We can see here that we are binding a few drivers into the container and then binding the MailManager on boot. Remember that our boot method has access to everything that has been registered into the container. The register methods are executed on all providers before the boot methods are executed.

Mail Manager

The MailManager here is important to understand. When the MailManager is instantiated, it accepts the container as a parameter. When the MailManager is instantiated, it fires a create_driver method which will grab the driver from the configuration file and retrieve a MailXDriver from the container. The create_driver method is a very simple method:

def create_driver(self, driver=None):
    if not driver:
        driver = self.container.make('MailConfig').DRIVER.capitalize()
    else:
        driver = driver.capitalize()

    try:
        self.manage_driver = self.container.make('Mail{0}Driver'.format(driver))
    except KeyError:
        raise DriverNotFound('Could not find the Mail{0}Driver from the service container. Are you missing a service provider?'.format(driver))

Notice that when the driver is created, it tries to get a Mail{0}Driver from the container. Therefore, all we need to do is register a MailXDriver into the container ('X' being the name of the driver) and Masonite will know to grab that driver.

Creating a Driver

So now we know that we need a MailXDriver so let's walk through how we could create a maildrill email driver.

We can simply create a class which can become our driver. We do not need to inherit anything, although Masonite comes with a BaseMailDriver to get you started faster and all drivers should inherit from it for consistency reasons. You can make your driver from a normal class object but it will be harder and won't be considered in Pull Requests.

Let's create a class anywhere we like and inherit from BaseMailDriver:

from masonite.driver.BaseMailDriver import BaseMailDriver

class MailMaildrillDriver(BaseMailDriver):
    pass

Great! We are almost done. We just have to implement one method on this class and that's the send method. All other methods like to and template are inherited from the BaseMailDriver class. You can find out how to send an email using Maildrill and implement it in this send method.

We can look at other drivers for inspiration but let's look at the MailMailgunDriver class now:

import requests
from masonite.drivers.BaseMailDriver import BaseMailDriver

class MailMailgunDriver(BaseMailDriver):

    def send(self, message=None):
        if not message:
            message = self.message_body

        domain = self.config.DRIVERS['mailgun']['domain']
        secret = self.config.DRIVERS['mailgun']['secret']
        return requests.post(
            "https://api.mailgun.net/v3/{0}/messages".format(domain),
            auth=("api", secret),
            data={"from": "{0} <mailgun@{1}>".format(self.config.FROM['name'], domain),
                  "to": [self.to_address, "{0}".format(self.config.FROM['address'])],
                "subject": self.message_subject,
                "html": message})

If you are wondering where the self.message_body and self.config are coming from, check the BaseMailDriver. All driver constructors are resolved by the service container so you can grab anything you need from the container to make your driver work. Notice here that we don't need a constructor because we inherited it from the BaseMailDriver

Registering Your Mail Driver

Our AppProvider class might look something like this:

from your.driver.module import MailMandrillDriver
class AppProvider(ServiceProvider):

    wsgi = True

    def register(self):
        self.app.bind('WebRoutes', web.ROUTES)
        self.app.bind('ApiRoutes', api.ROUTES)
        self.app.bind('Response', None)
        self.app.bind('Storage', storage)

        # Register new mail driver
        self.app.bind('MailMandrillDriver', MailMandrillDriver)

    def boot(self, Environ):
        self.app.bind('Request', Request(Environ))
        self.app.bind('Route', Route(Environ))

Great! Our new driver is registered into the container. It is now able to be created with Masonite's MailManager class. We can retrieve your new driver by doing:

def show(self, Mail)
    Mail.driver('mandrill') # fetches MailMandrillDriver from container

Configuration

If we want the MailManager to use our new driver by default, change the DRIVER in our config/mail.py file. In addition, you may have the users of your driver require a special dictionary entry to the DRIVERS dictionary:

DRIVERS = {
    'smtp': {
        'host': os.getenv('MAIL_HOST', 'smtp.mailtrap.io'),
        'port': os.getenv('MAIL_PORT', '465'),
        'username': os.getenv('MAIL_USERNAME', 'username'),
        'password': os.getenv('MAIL_PASSWORD', 'password'),
    },
    'mailgun': {
        'secret': os.getenv('MAILGUN_SECRET', 'key-XX'),
        'domain': os.getenv('MAILGUN_DOMAIN', 'sandboxXX.mailgun.org')
    },
    'maildrill': {
        'secret': 'xx'
        'other_key': 'xx'
    }
}

This way, users can easily swap drivers by simply changing the driver in the config file.

That's it! We just extended our Masonite project and created a new driver. Consider making it available on PyPi so others can install it!

Since the MailManager class creates the driver on boot, we can simply register the driver into the container via any service providers register method. We could create a new Service Provider and register it there. You can read more about created Service Providers under the documentation. For now, we will just register it from within our AppProvider.

Service Providers

Mail

Mail

Introduction

Masonite comes with email support out of the box. Most applications will need to send email upon actions like account creation or notifications. Because email is used so often with software applications, masonite provides mail support with several drivers.

Getting Started

By default, Masonite uses the smtp driver. Inside your .env file, just put your smtp credentials. If you are using Mailgun then switch your driver to mailgun and put your Mailgun credentials in your .env file.

Configuring Drivers

There are two drivers out of the box that masonite uses and there is a tiny bit of configuration for both.

SMTP Driver

The SMTP driver takes several configuration files we can all put in our .env file.

MAIL_DRIVER=smtp
MAIL_FROM_ADDRESS=admin@email.com
MAIL_FROM_NAME=Masonite
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=admin@email.com
MAIL_PASSWORD=password

Because this is SMTP, we can utilize all SMTP services such as mailtrap and gmail.

Thats it! As long as the authentication works, we can send emails. Remember that it is save to put sensitive data in your .env file because it is not committed to source control and it is inside the .gitignore file by default.

Mailgun Driver

Mailgun does not use SMTP and instead uses API calls to their service to send emails. Mailgun only requires 2 configuration settings:

MAIL_DRIVER=mailgun
MAILGUN_SECRET=key-xx
MAILGUN_DOMAIN=sandboxXX.mailgun.org

as well as changing the DRIVER inside config/mail.py

DRIVER = 'mailgun'

Masonite will retrieve the configuration settings for the mailgun driver from the DRIVERS configuration setting which Masonite has by default, you do not have to change this.

DRIVERS = {
    ...
    'mailgun': {
        'secret': os.getenv('MAILGUN_SECRET', 'key-XX'),
        'domain': os.getenv('MAILGUN_DOMAIN', 'sandboxXX.mailgun.org')
    }
}

Sending an Email

The Mail class is loaded into the container via the the MailProvider Service Provider. We can fetch this Mail class via our controller methods:

def show(self, Mail):
    print(Mail) # returns the default mail driver

We can send an email like so:

def show(self, Mail):
    Mail.to('hello@email.com').send('Welcome!')

All mail drivers are managed by the MailManager class and bootstrapped with the MailProvider Service Provider. Let's take a look at that:

class MailProvider(ServiceProvider):

wsgi = False

def register(self):
    self.app.bind('MailConfig', mail)
    self.app.bind('MailSmtpDriver', MailSmtpDriver)
    self.app.bind('MailMailgunDriver', MailMailgunDriver)
    self.app.bind('MailManager', MailManager(self.app))

def boot(self, MailConfig):
    self.app.bind('Mail',     MailManager(self.app).driver(MailConfig.DRIVER))

We can specify which driver we want to use. Although Masonite will use the DRIVER variable in our mail config file by default, we can change the driver on the fly.

You can see in our MailProvider Service Provider that we can use the MailManager class to set the driver. We can use this same class to change the driver:

def show(self, MailManager):
    MailManager.driver('mailgun') # now uses the Mailgun driver

Queues

Sending an email may take several seconds so it might be a good idea to create a Job. Jobs are simply Python classes that inherit from the Queueable class and can be pushed to queues or ran asynchronously. This will look something like:

from app.jobs.SendWelcomeEmail import SendWelcomeEmail

def show(self, Queue):
    Queue.push(SendWelcomeEmail)

Instead of taking seconds to send an email, this will seem immediate and be sent using whatever queue driver is set. The async driver is set by default which requires no additional configuration and simply sends jobs into a new thread to be ran in the background.

Read more about creating Jobs and sending emails asynchronously in the "Queues and Jobs" documentation.

Methods

We can specify which driver we want to use. Although Masonite will use the DRIVER variable in our config file, we can change the driver on the fly.

We can also specify the subject:

Mail.subject('Welcome!').to('hello@email.com').send('Welcome!')

You can specify which address you want the email to appear from:

Mail.send_from('Admin@email.com').to('hello@email.com').send('Welcome!')

Templates

If you don't want to pass a string as the message, you can pass a view template.

Mail.to('idmann509@gmail.com').template('mail/welcome').send()

This will render the view into a message body and send the email as html. Notice that we didn't pass anything into the send message

All mail configuration is inside config/mail.py and contains several well documented options. There are several built in drivers you can use but you can make your own if you'd like. You can follow the documentation here at . If you do make your own, consider making it available on PyPi so others can install it. We may even put it in Masonite by default.

Creating a Mail Driver

Uploading

Uploading

Introduction

Very often you will need to upload user images such as a profile image. Masonite let's you handle this very elegantly and allows you to upload to both the disk, and Amazon S3 out of the box. The UploadProvider Service Provider is what adds this functionality. Out of the box Masonite supports the disk driver which uploads directly to your file system and the s3 driver which uploads directly to your Amazon S3 bucket.

You may build more drivers if you wish to expand Masonite's capabilities. If you do create your driver, consider making it available on PyPi so others may install it into their project.

Read the "Creating an Email Driver" for more information on how to create drivers. Also look at the drivers directory inside the MasoniteFramework/core repository.

Configuration

All uploading configuration settings are inside config/storage.py. The settings that pertain to file uploading are just the DRIVER and the DRIVERS settings.

Driver and DRIVERS Settings

This setting looks like:

DRIVER = os.getenv('STORAGE_DRIVER', 'disk')

This defaults to the disk driver. The disk driver will upload directly onto the file system. This driver simply needs one setting which is the location setting which we can put in the DRIVERS dictionary:

DRIVERS = {
    'disk': {
        'location': 'storage/uploads'
    }
}

This will upload all images to the storage/uploads directory. If you change this directory, make sure the directory exists as Masonite will not create one for you before uploading. Know that the dictionary inside the DRIVERS dictionary should pertain to the DRIVER you set. For example, to set the DRIVER to s3 it will look like this:

DRIVER = 's3'

DRIVERS = {
    'disk': {
        'location': 'storage/uploads'
    },
    's3': {
        'client': os.getenv('S3_CLIENT', 'AxJz...'),
        'secret': os.getenv('S3_SECRET', 'HkZj...'),
        'bucket': os.getenv('S3_BUCKET', 's3bucket'),
    }
}

Some deployment platforms are Ephemeral. This means that either hourly or daily, they will completely clean their file systems which will lead to the deleting of anything you put on the file system after you deployed it. In other words, any user uploads will be wiped. To get around this, you'll need to upload your images to Amazon S3 or other asset hosting services which is why Masonite comes with Amazon S3 capability out of the box.

Uploading

Uploading with masonite is extremely simple. We can use the Upload class which is loaded into the container via the UploadProvider Service Provider. Whenever a file is uploaded, we can retrieve it using the normal Request.input() method. This will look something like:

<html>
    <body>
    <form action="/upload" method="POST" enctype="multipart/form-data">
        <input type="file" name="file_upload">
    </form>
    </body>
</html>

And inside our controller we can do:

def upload(self, Upload):
    Upload.driver('disk').store(Request.input('file_upload'))

That's it! We specified the driver we want to use and just uploaded an image to our file system.

This action will return the file system location. We could use that to input into our database if we want:

>>> Upload.driver('disk').store(Request.input('file_upload'))
storage/uploads/new_upload.png

We may also need to get the filename of the upload. If the request input is a file upload, we have some additional attributes we can use:

>>> Request.input('file_upload')
new_upload.png

Lastly, we may need to prepend the file name with something like a uuid or something or even just a normal string. We can do so by using the storePrepend() method:

>>> Upload.driver('disk').store(Request.input('file_upload'), 'prepend_name_')
prepend_name_newupload.png

Uploading to S3

Uploading to S3 is exactly the same. Simply add your username, secret key and bucket to the S3 setting:

DRIVER = 's3'

DRIVERS = {
    'disk': {
        'location': 'storage/uploads'
    },
    's3': {
        'client': os.getenv('S3_CLIENT', 'AxJz...'),
        'secret': os.getenv('S3_SECRET', 'HkZj...'),
        'bucket': os.getenv('S3_BUCKET', 's3bucket'),
    }
}

Make sure that your user has the permission for uploading to your S3 bucket.

Then in our controller:

def upload(self, Upload):
    Upload.driver('s3').store(Request.input('file_upload'))

How the S3 driver currently works is it uploads to your file system using the disk driver, and then uploads that file to your Amazon S3 bucket. So do not get rid of the disk setting in the DRIVERS dictionary.

View Composers and Sharing

View Composers and Sharing

Introduction

Very often you will find yourself adding the same variables to a view again and again. This might look something like

def show(self):
    return view('dashboard', {'request': request()})

def another_method(self):
    return view('dashboard/user', {'request': request()})

This can quickly become annoying and it can be much easier if you can just have a variable available in all your templates. For this, we can "share" a variable with all our templates with the View class.

The View class is loaded into our container under the ViewClass alias. It's important to note that the ViewClass alias from the container points to the class itself and the View from the container points to the View.render method. By looking at the ViewProvider this will make more sense:

class ViewProvider(ServiceProvider):

    wsgi = False

    def register(self):
        view = View()
        self.app.bind('ViewClass', view)
        self.app.bind('View', view.render)

As you can see, we bind the view class itself to ViewClass and the render method to the View alias.

View Sharing

We can share variables with all templates by simply specifying them in the .share() method like so:

ViewClass.share({'request': request()})

The best place to put this is in a new Service Provider. Let's create one now called ViewComposer.

$ craft provider ViewComposer

This will create a new Service Provider under app/providers/ViewComposer.py and should look like this:

class ViewComposer(ServiceProvider):

    def register(self):
        pass

    def boot(self):
        pass

We also don't need it to run on every request so we can set wsgi to False. Doing this will only run this provider when the server first boots up. This will minimize the overhead needed on every request:

class ViewComposer(ServiceProvider):

    wsgi = False

    def register(self):
        pass

    def boot(self):
        pass

Great!

Since we need the request, we can throw it in the boot method which has access to everything registered into the service container, including the Request class.

class ViewComposer(ServiceProvider):

    wsgi = False

    def register(self):
        pass

    def boot(self, ViewClass, Request):
        ViewClass.share({'request': Request})

Lastly we need to load this into our PROVIDERS list inside our config/application.py file.

PROVIDERS = [
    # Framework Providers
    ...
    'masonite.providers.ViewProvider.ViewProvider',
    'masonite.providers.HelpersProvider.HelpersProvider',

    # Third Party Providers

    # Application Providers
    'app.providers.UserModelProvider.UserModelProvider',
    'app.providers.MiddlewareProvider.MiddlewareProvider',
    'app.providers.ViewComposer.ViewComposer', # <- New Service Provider
]

And we're done! When you next start your server, the request variable will be available on all templates.

View Composing

In addition to sharing these variables with all templates, we can also specify only certain templates. All steps will be exactly the same but instead of the .share() method, we can use the .compose() method:

def boot(self, ViewClass, Request):
    ViewClass.compose('dashboard', {'request': Request})

Now anytime the dashboard template is accessed (the one at resources/templates/dashboard.html) the request variable will be available.

We can also specify several templates which will do the same as above but this time with the resources/templates/dashboard.html template AND the resources/templates/dashboard/user.html template:

def boot(self, ViewClass, Request):
    ViewClass.compose(['dashboard', 'dashboard/user'], {'request': Request})

Lastly, we can compose a dictionary for all templates:

def boot(self, ViewClass, Request):
    ViewClass.compose('*', {'request': Request})

Note that this has exactly the same behavior as ViewClass.share()

Broadcasting

Broadcasting

Introduction

Masonite understands the developer need for building modern web applications so Masonite 1.4+ ships with WebSocket support. With a new Service Provider, configuration file and support for the pusher and ably drivers out of the box, we can now have full web socket support quickly and easily.

Configuration

All broadcasting configuration is located in the config/broadcast.py file. There are only two options: DRIVER and DRIVERS. The DRIVER should hold the value of the driver you want to use such as pusher:

DRIVER = 'pusher'

and DRIVERS should hold the configuration data:

DRIVERS = {
    'pusher': {
        'app_id': os.getenv('PUSHER_APP_ID', '29382xx..'),
        'client': os.getenv('PUSHER_CLIENT', 'shS8dxx..'),
        'secret': os.getenv('PUSHER_SECRET', 'HDGdjss..'),
    },
    'ably': {
        'secret': os.getenv('ABLY_SECRET', 'api:key')
    }
}

Each driver may require it's own individual setting values so be sure to check the documentation for the driver you are using. For the ably and pusher drivers, these are the only values you will need.

Make sure that the key in the DRIVER setting has a corresponding key in the DRIVERS setting.

Usage

Since we have a ServiceProvider Service Provider which takes care of the container bindings for us, we can now it simply by passing Broadcast into our parameter list in our controller methods like so:

def show(self, Broadcast):
    print(Broadcast) # prints the driver class

We can change the driver on the fly as well:

def show(self, Broadcast):
    print(Broadcast.driver('ably')) # prints the ably driver class

All drivers have the same methods so don't worry about different drivers having different methods.

Channels

We can send data through our WebSocket by running:

def show(self, Broadcast):
    Broadcast.channel('channel_name', 'message')

That's it! we have just sent a message to anyone subscribed to the channel_name channel.

We can also send a dictionary:

def show(self, Broadcast):
    Broadcast.channel('channel_name', {'message': 'hello world'})

We can also send a message to multiple channels by passing a list:

def show(self, Broadcast):
    Broadcast.channel(['channel1', 'channel2'], {'message': 'hello world'})

This will broadcast the message out to both channels. We can pass as many channels into the list as we like.

Masonite also has an optional third parameter which is the event name:

def show(self, Broadcast):
    Broadcast.channel('channel_name', 'message', 'subscribed')

Which will pass the event on to whoever is receiving the WebSocket.

Caching

Caching

Introduction

Caching is an important aspect to any project and typically is used to speed up data that never changes and required a lot of resources to get. Powerful caching support is important in any application and Masonite comes with great caching support out of the box.

Getting Started

We need the CacheProvider in order to activate caching with Masonite. We do so simple by going to our config/application.py file and adding the Service Provider masonite.providers.CacheProvider.CacheProvider to the PROVIDERS list.

All configuration settings are inside the config/cache.py file. Masonite only comes with a simple disk driver which stores all of your cache on the file system.

By default, Masonite will store the cache under the bootstrap/cache directory but can be changed simply inside the DRIVERS dictionary in the config/cache.py file. For example to change from bootstrap/cache to the storage/cache/templates directory, this will look like:

DRIVERS = {
    'disk': {
        'location': 'storage/cache/templates'
    }
}

Using the Cache

To start using the cache, we can use the Cache alias that is loaded into the container from the CacheProvider Service Provider. We can retrieve this from the container inside any method that is resolved by the container such as drivers, middleware and controllers. For example we can retrieve it from our controller method like so:

def show(self, Cache):
    Cache # returns the cache class

Storing

We can easily store items into the cache by doing:

def show(self, Cache):
    Cache.store('key', 'value')

This will create a bootstrap/cache/key.txt file which contains a simple value.

Caching For Time

We may only want to cache something for a few seconds or a few days so we can do something like:

def show(self, Cache):
    Cache.store_for('key', 'value', 5, 'seconds')

This will store the cache for 5 seconds. If you try to retrieve this value after 5 seconds, the Cache class will return None so be sure to check.

Getting

It wouldn't be very good if we could only store values and not retrieve them. So we can also do this simple by doing:

def show(self, Cache):
    Cache.get('key')

Again this will return None if a cache is expired. If there is no time limit on the cache, this will simply always return the cache value.

Checking Validity

You can also explicitly check if a cache is still valid by doing:

def show(self, Cache):
    Cache.is_valid('key')

This will return a boolean if a key is valid. This means it is not expired.

Checking Cache Exists

We'll have to sometimes check if a cache even exists so we can do that by running:

def show(self, Cache):
    Cache.cache_exists('key')

Which will return a boolean if the cache exists or not.

Deleting

You can delete a cache by key using:

def show(self, Cache):
    Cache.delete('key')

Remember that Masonite uses a Service Container and automatic dependency injection. You can read more about it under the documentation.

Service Container

Queues and Jobs

Queues and Jobs

Introduction

Almost all applications can make use of queues. Queues are a great way to make time intensive tasks immediate by sending the task into the background. It's great to send anything and everything into the queue that doesn't require an immediate return value -- such as sending an email or firing an API call. The queue system is loaded into masonite via the QueueProvider Service Provider.

Getting Started

All configuration settings by default are in the config/queue.py file. Out of the box, Masonite only supports the async driver which simply sends jobs into the background using multithreading. You are free to create more drivers. If you do create a driver, consider making it available on PyPi so others can also install it.

Jobs

Jobs are simply Python classes that inherit the Queueable class that is provided by Masonite. We can simply create jobs using the craft job command.

$ craft job SendWelcomeEmail

This will create a new job inside app/jobs/SendWelcomeEmail.py. Our job will look like:

from masonite.queues.Queueable import Queueable

class SendWelcomeEmail(Queueable):

    def __init__(self):
        pass

    def handle(self):
        pass

All job constructors are resolved by the container so we can simply pass anything we need as normal:

from masonite.queues.Queueable import Queueable

class SendWelcomeEmail(Queueable):

    def __init__(self, Request, Mail):
        self.request = Request
        self.mail = Mail

    def handle(self):
        pass

Whenever jobs are executed, it simply executes the handle method. Because of this we can send our welcome email:

from masonite.queues.Queueable import Queueable

class SendWelcomeEmail(Queueable):

    def __init__(self, Request, Mail):
        self.request = Request
        self.mail = Mail

    def handle(self):
        self.mail.driver('mailgun').to(self.request.user().email).template('mail/welcome').send()

That's it! We just created a job that can send to to the queue!

Running Jobs

We can run jobs by using the Queue alias from the container. Let's run this job from a controller method:

from app.jobs.SendWelcomeEmail import SendWelcomeEmail

def show(self, Queue):
    Queue.push(SendWelcomeEmail)

That's it! This job will be loaded into the queue. By default, Masonite uses the async driver which just sends tasks into the background.

We can also send multiple jobs to the queue by passing more of them into the .push() method:

from app.jobs.SendWelcomeEmail import SendWelcomeEmail
from app.jobs.TutorialEmail import TutorialEmail

def show(self, Queue):
    Queue.push(SendWelcomeEmail, TutorialEmail)

Remember that anything that is resolved by the container is able to retrieve anything from the container by simply passing in parameters of objects that are located in the container. Read more about the container in the documentation.

Service Container

Compiling Assets

Compiling Assets

Introduction

Understanding that modern frameworks need to handle modern web applications. Many developers are starting to use third party packages, like Sass, to write CSS. Normally, many people who write Sass in other frameworks will need to run other third party services like Webpack or grunt. Masonite tries to make this as simple as possible and comes with Sass built in. So you just need to write Sass and it will compile into CSS when you run the server.

Getting Started

Now although Masonite comes with the ability to compile Sass, it is deliberately missing the libsass dependency. This dependency takes several minutes to install and therefore was left out of the requirements to speed up the process of creating a new project.

Masonite can compile all of your Sass into CSS files when you run the server. The code needed to compile Sass is already inside the framework although it does not execute without libsass .

In order to activate this feature we can run:

pip install libsass

Awesome! We're good to go. All Sass put inside resources/static will compile into resources/compiled .

Configuration

Masonite comes with a configuration file that will allow you to tweak the locations of files that Sass will be looked for, as well as where it will compile into. This setting page can be found in config/storage.py . The configuration constant looks something like:

SASSFILES = {
    'importFrom': [
        'storage/static'
    ],
    'includePaths': [
        'storage/static/sass'
    ],
    'compileTo': 'storage/compiled'
}

ImportFrom Setting

This setting will look for base .sass and .scss files. Base Sass files are files without a preceding underscore. So style.scss is a base Sass file but _dashboard.scss is not. Once all the base Sass files are found, it will compile them into CSS and put them in the location specifed in the compileTo setting.

IncludePaths Setting

This setting is where Masonite will look for files anytime you want to include using the @include keyword in your sass files. Without the correct location here, Masonite will not find any files you include in your Sass files. This setting can be a list of directory locations.

CompileTo Setting

This setting specifies a single directory you want all of your Sass compiled down into.

This is all setup by default for you and works as soon as you install the libsass dependency.

Validation

Validation

Introduction

Very often you will find a need to validate forms after you have submitted them. Masonite comes with a very simple and reusable way to validate input data with the Masonite Validator() class. In this documentation, we'll talk about how you can create your own validator to use within your project. Masonite uses the validator.py library for this feature.

Getting Started

The best way to create a reusable validator class within your Masonite project is to create a class and inherit from the Validator class inside the masonite.validator module.

We can make a class called RegistrationValidator(), inherit from masonite.validator.Validator() and put it inside app/validators/RegistrationValidator.py like so:

from masonite.validator import Validator

class RegistrationValidator(Validator):

    def register_form(self):
        pass

Awesome! By inheriting from Validator, this will add several key methods to our validator class that we'll need to verify our request input which we'll talk about below.

Starting Our Validations

Since we inherited from Validator, we have access to a validate() method which we can call with self.validate(). Inside this method call, we can use some useful attributes in order to check our request data.

An example of a simple validation will look something like:

from masonite.validator import Validator
from validate import Required, Pattern, Truthy

class RegistrationValidator(Validator):

    def register_form(self):
        self.validate(
            'username': [Required, Pattern('[a-zA-Z0-9]')]
            'is_staff': [Required, Truth()],
            'password': [Required]
        )

Custom Error Messages

By default, Masonite will supply you with a dictionary of errors depending on the validator class. More information on what the default error messages are found below.

Although this is very convenient, you may wish to specify your own error messages. To do so, we can call the self.messages() method after we validate. This will look like:

from masonite.validator import Validator
from validate import Required, Pattern, Truthy

class RegistrationValidator(Validator):

    def register_form(self):
        self.validate({
            'username': [Required, Pattern('[a-zA-Z0-9]')]
            'is_staff': [Required, Truth()],
            'password': [Required]
        })

        self.messages({
            'username': 'The username is required!',
            'password': 'Make this password top secret!'
        })

This will change the default error messages to the defaults provided. If you do not specify a custom error message for a validation field then the default one will display as usual.

Requests

In order to check the input data we receive from a request, such as a form submission, we can use this validator like so:

from app.validators.RegistrationValidator import RegistrationValidator

def show(self, Request):
    validate = RegistrationValidator(Request)
    validate.register_form()
    validate.check() # returns True or False
    validate.errors() # returns a dictionary of errors if any

Notice that we pass in the request inside the constructor of our RequestValidator class. Our class is using the constructor inherited from Masonite's Validator class.

Non Requests

Sometimes we may wish to use our validator class without request data. In order to do this we can just pass a dictionary of values into our .check() method like so:

from app.validators.RegistrationValidator import RegistrationValidator

def show(self):
    validate = RegistrationValidator()
    validate.register_form()
    validate.check({'username': 'John'}) # returns True or False
    validate.errors() # returns a dictionary of errors if any

Notice how we passed a dictionary into our .check() method here and didn't pass the request object in the constructor.

Validator Options

There are a plethora of options that you can use to validate your forms. In addition to validating your request input, we also get a dictionary of errors. In order to get the errors if a validation fails, we can get use the method:

validate.errors() # {'username': 'must be present'}

This method will return a dictionary of errors that will be different depending on the validation class used but this method will return None if there are no errors. Below each option will be what the value of .errors() will be as well as how you would use them inside Masonite.

Required

By default, all keys registered for validation are optional. Any key that doesn't exist in the validation will skip any of the missing input data. For example, if a validation is not set for password then it will simply not check any validation on that specific request input. In this case, we can leave our password validation out entirely.

Unlike other validator classes, this class does not need to be instantiated (contain parenthesis at the end). So Required is the correct usage and not Required().

Usage

from validate import Required

self.validate({
    'username': [Required]
})

Error

{"username": ["must be present"]}

Truthy

The Truthy() validator class will check whatever is truthy to Python. This includes True, non-0 integers, non-empty lists, and strings

Usage

from validate import Truthy

self.validate({
    'username': [Truthy()]
})

Error

{"username": ["must be True-equivalent value"]}

Equals

This validator will check that a value is equal to the value given.

Usage

from validate import Equals

self.validate({
    'username': [Equals('Joseph')]
})

Error

{"username": ["must be equal to 'Joseph'"]}

Note that all request input data will be a string. so make sure you use Equals('1') and not Equals(1). Just be sure to maintain the data type in your validation.

Range

This validator checks that the dictionary value falls inclusively between the start and end values passed to it.

from validate import Range

self.validate({
    'age': [Range(1, 100)]
})

Error

{"age": ["must fall between 1 and 100"]}

Pattern

The Pattern validator checks that the dictionary value matches the regex pattern that was passed to it.

Usage

from validate import Pattern

self.validate({
    'age': [Pattern('\d+')]
})

Error

{"age": ["must match regex pattern \d+"]}

### In
****

This validator checks that the dictionary value is a member of a collection passed to it.


#### Usage

```python
from validate import In

self.validate({
    'username': [In(['Joseph', 'Michael', 'John'])]
})

Since Orator returns a collection, we can specify an Orator Collection as well:

from validate import In
from config import database
users = db.table('users').select('name').get()

self.validate({
    'username': [In([users])]
})

Error

{"age": ["must be one of <collection here>"]}

Not

This validator negates a validator that is passed to it and checks the dictionary value against that negated validator.

Usage

from validate import Not
from config import database
users = db.table('users').select('name').get()

self.validate({
    'age': [Not(In(users))]
})

Error

{"age": ["must be one of <collection here>"]}

InstanceOf

This validator checks that the dictionary value is an instance of the base class passed to it, or an instance of one of its subclasses.

Usage

from validate import InstanceOf

self.validate({
    'age': [InstanceOf(basestring)]
})

Error

{"age": ["must be an instance of basestring or its subclasses"]}

SubclassOf

This validator checks that the dictionary value inherits from the base class passed to it. To be clear, this means that the dictionary value is expected to be a class, not an instance of a class.

Usage

from validate import SubclassOf

self.validate({
    'age': [SubclassOf(str)]
})

Error

{"age": ["must be a subclass of str"]}

Length

This validator checks that value the must have at least minimum elements and optionally at most maximum elements.

Usage

from validate import Length

self.validate({
    'age': [Length(0, maximum=5)]
})

Error

{"age": ["must be at most 5 elements in length"]}

Authentication

Authentication

Introduction

Masonite comes with some authentication out of the box but leaves it up to the developer to implement. Everything is already configured for you by default. The default authentication model is the app/User model but you can change this in the config/auth.py configuration file.

Configuration

There is only a single config/auth.py configuration file which you can use to set the authentication behavior of your Masonite project. If you wish to change the authentication model, to a app/Company model for example, feel free to do in this configuration file.

Authentication Model

Again the default authentication model is the app/User model which out of the box comes with a __auth__ class attribute. This attribute should be set to the column that you want to authenticate with. By default your app/User model will default to the email column but if you wish to change this to another column such as name, you can do so here. This will lead your model to look like:

class User(Model):

    __fillable__ = ['name', 'email', 'password']

    __auth__ = 'name'

All models that should be authenticated in addition to specifying a __auth__ attribute also needs to have a password field as well in order to use the out of the box authentication that comes with Masonite.

Authenticating a Model

If you want to authenticate a model, you can use the Auth facade that ships with Masonite. This is simply a class that is used to authenticate models with a .login() method.

In order to authenticate a model this will look like:

from masonite.facades.Auth import Auth

def show(self, Request):
    Auth(Request).login('user@email.com', 'password')

This will find a model with the supplied username, check if the password matches using bcrypt and return the model. If it is not found or the password does not match, it will return False.

Again all authenticating models need to have a password column. The column being used to authenticate, such as a username or email field can be specified in the model using the __auth__ class attribute.

Changing The Authentication Column

You may change the column to be authenticated by simply changing the column value of the __auth__ class attribute. This will look something like:

class User(Model):

    __fillable__ = ['name', 'email', 'password']

    __auth__ = 'email'

This will look inside the email column now and check that column and password. The authentication column is email by default.

Creating an Authentication System

You may of course feel free to roll your own authentication system if you so choose but Masonite comes with one out of the box but left out by default. In order to scaffold this authentication system you can of course use a craft command:

$ craft auth

This will create some controllers, views and routes for you. This command should be used primarily on fresh installs of Masonite but as long as the controllers do not have the same names as the controllers being scaffolded, you will not have any issues.

The views scaffolded will be located under resources/templates/auth.

After you have ran the craft auth command, just run the server and navigate to http://localhost:8000/login and you will now have a login, registration and dashboard. Pretty cool, huh?

Retrieving the Authenticated User

Masonite ships with a LoadUser middleware that will load the user into the request if they are authenticated. Masonite uses the token cookie in order to retrieve the user using the remember_tokencolumn in the table.

Using this LoadUser middleware you can retrieve the current user using:

def show(self, Request):
    Request.user()

If you wish not to use middleware to load the user into the request you can get the request by again using the Auth class

from masonite.facades.Auth import Auth

def show(self, Request):
    Auth(Request).user()

Checking if the User is Authenticated

If you would like to simply check if the user is authenticated, Request.user() or Auth(Request).user() will return False if the user is not authenticated. This will look like:

def show(self, Request):
    if Request.user():
        user_email = Request.user().email

Protecting Routes

Masonite ships with an authentication middleware. You can use this middleware as a route middleware to protect certain routes from non authenticated users. This is great for redirecting users to a login page if they attempt to go to their dashboard.

You can use this middleware in your routes file like so:

Get().route('/dashboard', 'DashboardController@show').middleware('auth')

By default this will redirect to the route named login. If you wish to redirect the user to another route or to a different URI, you can edit the middleware in app/http/middleware/AuthenticationMiddleware.py

Logging Out a User

If you wish to end the session for the user and log them out, you can do so by using the Auth class. This looks like:

Auth(request).logout()

This will delete the cookie that was set when logging in. This will not redirect the user to where they need to go. A complete logout view might look like:

def logout(self, Request):
    Auth(Request).logout()
    return Request.redirect('/login')

Great! You’ve mastered how Masonite uses authentication. Remember that this is just out of the box functionality and you can create a completely different authentication system but this will suffice for most applications.

CSRF Protection

CSRF Protection

Introduction

Masonite 1.4+ now has out of the box CSRF protection. CSRF, or Cross-Site Request Forgery is when malicious actors attempt to send requests (primarily POST requests) on your behalf. CSRF protection typically entails setting a unique token to the user for that page request that matches the same token on the server. This prevents any person from submitting a form without the correct token. There are many online resources that teach what CSRF does and how it works but Masonite makes it really simple to use.

If you are using Masonite 1.4 already then you already have the correct middleware and Service Providers needed. You can check which version of Masonite you are using by simply running pip show masonite and looking at the version number.

Getting Started

Usage

The CSRF features for Masonite are located in the CsrfProvider Service Provider and the CsrfMiddleware. If you do not wish to have CSRF protection then you can safely remove both of these.

The CsrfProvider simply loads the CSRF features into the container and the CsrfMiddleware is what actually generates the keys and checks if they are valid.

Templates

By default, all POST requests require a CSRF token. We can simply add a CSRF token in our forms by adding the {{ csrf_field|safe }} tag to our form like so:

<form action="/dashboard" method="POST">
    {{ csrf_field|safe }}

    <input type="text" name="first_name">
</form>

This will add a hidden field that looks like:

<input type="hidden" name="csrf_token" value="8389hdnajs8...">

If this token is changed or manipulated, Masonite will throw an InvalidCsrfToken exception from inside the middleware.

If you attempt a POST request without the {{ csrf_field|safe }} then you will receive a KeyError: 'csrf_token' exception. This just means you are either missing the Jinja2 tag or you are missing that route from the exempt class attribute in your middleware.

Exempting Routes

Not all routes may require CSRF protection such as OAuth authentication. In order to exempt routes from protection we can add it to the exempt class attribute in the middleware located at app/http/middleware/CsrfMiddleware.py:

class CsrfMiddleware:
    ''' Verify CSRF Token Middleware '''

    exempt = [
        '/oauth/github'
    ]

    ...

Now any POST routes that are to your-domain.com/oauth/github are not protected by CSRF. Use this sparingly as CSRF protection is crucial to application security but you may find that not all routes need it.

Encryption

Encryption

Introduction

Background

Also, we make sure that Javascript cannot read your cookies. It's important to know that although your website may be secure, you are susceptible to attacks if you import third party Javascript packages (since those libraries could be hackable) which can read all cookies on your website and send them to the hacker.

Other frameworks use cryptographic signing which attached a special key to your cookies that prevents manipulation. This does't make sense as a major part of XSS protection is preventing third parties from reading cookies. It doesn't make sense to attach a digital signature to a plaintext cookie if you don't want third parties to see the cookie (such as a session id). Masonite takes one step further and encrypts the entire string and can only be decrypted using your secret key (so make sure you keep it secret).

Secret Key

In your .env file, you will find a setting called KEY=your-secret-key. This is the SALT that is used to encrypt and decrypt your cookies. It is important to change this key sometime before development. Masonite does not currently set this key for you. You can generate new secret keys by running:

This will generate a new key in your terminal which you can copy and paste into your .env file. Your config/application.py file uses this environment variable to set the KEY configuration setting.

Additionally you can pass the --store flag which will automatically set the KEY= value in your .env file for you:

Remember to not share this secret key as a loss of this key could lead to someone being able to decrypt any cookies set by your application. If you find that your secret key is compromised, just generate a new key.

Cryptographic Signing

You can use the same cryptographic signing that Masonite uses to encrypt cookies on any data you want. Just import the masonite.sign.Sign class. A complete signing will look something like:

By default, Sign() uses the encryption key in your config/application.py file but you could also pass in your own key.

Just remember to store the key you generated or you will not be able to decrypt any values that you encrypted.

Using bcrypt

Bcrypt is very easy to use an basically consists of a 1 way hash, and then a check to verify if that 1 way hash matches an input given to it. It's important to note that any values passed to bcrypt need to be in bytes.

Hashing Passwords

Again, all values passed into bcrypt need to be in bytes so we can has a password

Notice that the value passed in from the request was converted into bytes using the bytes() Python function.

Once the password is hashed, we can just safely store it into our database

Do not store unhashed passwords in your database. Also, do not use unsafe encryption methods like MD5 or SHA-1.

Checking Hashed Passwords

In order to check if a password matches it's hashed form, such as trying to login a user, we can use the bcrypt.checkpw() function:

This will return true if the string 'password' is equal to the models password.

More information on bcrypt can be found by reading it's documentation.

If you are running a version of Masonite before 1.4 then check the upgrade guide for for learning how to upgrade.

Masonite comes with bcrypt out of the box but leaves it up to the developer to actually encrypt things like passwords. You can opt to use any other hashing library but bcrypt is the standard of a lot of libraries and comes with some one way hashing algorithms with no known vulnerabilities. Many of hashing algorithms like SHA-1 and MD5 are not secure and you should not use them in your application. You can read the .

This feature uses for this kind of encryption. Because of this, we can generate keys using Fernet.

Masonite 1.3 to 1.4
$ craft key
$ craft key --store
from masonite.auth.Sign import Sign

sign = Sign()

sign.encrypt('value') # PSJDUudbs87SB....

sign.decrypt('value') # 'value'
from masonite.auth.Sign import Sign

encryption_key = b'SJS(839dhs...'

sign = Sign(encryption_key)

sign.encrypt('value') # PSJDUudbs87SB....

sign.decrypt('value') # 'value'
from masonite.auth.Sign import Sign
from cryptography.fernet import Fernet

encryption_key = Fernet.generate_key()

sign = Sign(encryption_key)

sign.encrypt('value') # PSJDUudbs87SB....

sign.decrypt('value') # 'value'
password = bcrypt.hashpw(
                bytes(request.input('password'), 'utf-8'), bcrypt.gensalt()
            )
User.create(
    name=request.input('name'),
    password=password,
    email=request.input('email'),
)
bcrypt.checkpw(bytes('password', 'utf-8'), bytes(model.password, 'utf-8'))
bcrypt documentation here
pyca/cryptography

Database Migrations

Database Migrations

Introduction

Database migrations in Masonite is very different than other Python frameworks. Other Python frameworks create migrations based on a model which historically uses Data Mapper type ORM's. Because Masonite uses an Active Record ORM by default, Migrations are completely separated from models. This is great as it allows a seamless switch of ORM's without interfering with migrations. In addition to creating this separation of migrations and models, it makes managing the relationship between models and tables extremely basic with very little magic which leads to faster debugging as well as fewer migration issues.

In this documentation, we'll talk about how to make migrations with Masonite.

Getting Started

Because models and migrations are separated, we never have to touch our model in order to make alterations to our database tables. In order to make a migration we can run a craft command:

$ craft migration name_of_migration_here --table dashboard

This command will create a migration for an existing table. A migration on an existing table will migrate into the database in a certain way so it's important to specify the --table flag in the command.

In order to create a migration file for a new table that doesn't yet exist (but will after the migration) you can instead use the --create flag like so:

$ craft migration name_of_migration_here --create dashboard

This will create a migration that will create a table, as well as migrate the columns you specify.

Migrating Columns

Inside the migration file you will see an up() method and a down() method. We are only interested in the up() method. This method specifies what to do when the migration file is migrated. The down() method is what is executed when the migration is rolled back. Lets walk through creating a blog migration.

$ craft migration create_blogs_table --create blogs

This will create a migration file located in databases/migrations . Lets open this file and add some columns.

After we open it we should see something an up() method that looks like this:

def up(self):
        """
        Run the migrations.
        """
        with self.schema.create('blogs') as table:
            table.increments('id')
            table.timestamps()

Inside our with statement we can start adding columns.

Lets go ahead and add some columns that can be used for a blog table.

def up(self):
        """
        Run the migrations.
        """
        with self.schema.create('blogs') as table:
            table.increments('id')
            table.string('title')
            table.text('body')
            table.integer('active')
            table.integer('user_id').unsigned()
            table.foreign('user_id').references('id').on('users')
            table.timestamps()

Ok let's go ahead and break down what we just created.

Foreign Keys

So adding columns is really straight forward and Orator has some great documentation on their website. In order to add a foreign key, we'll need an unsigned integer column which we specified above called:

table.integer('user_id').unsigned()

This will set up our column index to be ready for a foreign key. We can easily specify a foreign key by then typing

table.foreign('user_id').references('id').on('users')

What this does is sets a foreign key on the user_id column which references the id column on the users table. That's it! It's that easy and expressive to set up a foreign key.

Changing Columns

There are two types of columns that we will need to change over the course of developing our application. Changing columns is extremely simple. If you're using MySQL 5.6.6 and below, see the caveat below.

To change a column, we can just use the .change() method on it. Since we need to create a new migration to do this, we can do something like:

$ craft migration change_default_status --table dashboard

and then simply create a new migration but use the .change() method to let Masonite you want to change an existing column instead of adding a new one:

table.integer('status').nullable().default(0).change()

When we run craft migrate it will change the column instead of adding a new one.

Changing Foreign Keys Prior to MySQL 5.6.6

Because of the constraints that foreign keys put on columns prior to MySQL 5.6.6, it's not as straight forward as appending a .change() to the foreign key column. We must first:

  • drop the foreign key relationship

  • change the column

  • recreate the foreign key

We can do this simply like so:

table.drop_foreign('posts_user_id_foreign')
table.rename_column('user_id', 'author_id')
table.foreign('author_id').references('id').on('users')

About Managers

About Managers

Introduction

Masonite uses an extremely powerful pattern commonly known as the Manager Pattern; also known as the Builder Pattern. Because Masonite uses classes with the XManager namespace, we will call it the Manager Pattern throughout this documentation.

Think of the Manager Pattern as attaching a Manager to a specific feature. This Manager is responsible for instantiating FeatureXDriver classes. For example, we attach a UploadManager to the upload feature. Now the UploadFeature will instantiate UploadXDriver classes.

For an actual example inside Masonite, there are currently two classes for the Upload feature: UploadDiskDriver and UploadS3Driver. Whenever we set the DRIVER in our config/storage.py file to s3, the UploadManager will use the UploadS3Driver to store our files.

This is extremely useful for extending functionality of the managers. If we need to upload to Google, we can just make a UploadGoogleDriver and put it inside the container. If we set our configuration DRIVER to google, our UploadManager will now use that class to store files.

Creating a Manager

Masonite obviously comes with several managers such as the UploadManager and the MailManager. Let's walk through how to create a new manager called the TaskManager.

Managers can live wherever they want but if you are developing a manager for the Masonite core package, they will be placed inside masonite/managers.

Let's create a new file: masonite/managers/TaskManager.py.

Great! Now all managers should inherit from the masonite.managers.Manager class. Our TaskManager should look something like:

Awesome! Inheriting from the Manager class will give our manager almost all the methods it needs. The only thing we need now is to tell this manager how to create drivers. So to do this all we need are two attributes:

Perfect. Managers are both extremely powerful and easy to create. That's it. That's our entire provider. The config attribute is the configuration file you want which is key in the container and the driver_prefix is the drivers you want to manager. In this case it is the TaskDriver. This manager will manage all drivers in the container that conform to the namespaces of Task{0}Driver like TaskTodoDriver and TaskNoteDriver.

Notice that the config is TaskConfig and not task. This attribute is the binding name and not the config name. We can bind the task config into the container like so:

Which will be required to use our new task manager since it relies on the task configuration. You can do this inside the Service Provider that will ship with this manager. We will create a Service Provider later on but for now just know that that's where that configuration comes from.

Using Our Manager

Great! We can put this Service Provider in our app/application.py file inside the PROVIDERS list. Once that is inside our providers list we can now use this new Task alias in our controllers like so:

Notice that we binded the TaskManager into the container under the Task key. Because of this we can now pass the Task in any parameter set that is resolved by the container like a controller method. Since we passed the Task into the parameter set, Masonite will automatically inject whatever the Task key from the container contains.

We can use in order to build our migration file. First lets run a migration craft command to create a blog table:

Notice that we are using a context processor which is our schema builder. All we have to worry about is whats inside it. Notice that we have a table object that has a few methods that are related to columns. Most of these columns are pretty obvious and you can read about different you can use. We'll mention the foreign key here though.

Check the for more information on creating a migration file.

We can use our manager simply by loading it into the container. We can do this by creating a Service Provider. Learn more about how to create a Service Provider in the documentation. Let's show what a basic Service Provider might look like:

Read about how to create drivers for your Manager class under the documentation.

Orators Schema Builder
Orator Schema Columns
Orator documentation
from masonite.managers.Manager import Manager

class TaskManager(Manager):
    pass
from masonite.managers.Manager import Manager

class TaskManager(Manager):

    config = 'TaskConfig'
    driver_prefix = 'Task'
from config import task

container.bind('TaskConfig', task)
from masonite.provider import ServiceProvider
from masonite.drivers.TaskTodoDriver import TaskTodoDriver
from masonite.managers.TaskManager import TaskManager
from config import task

class TaskProvider(ServiceProvider):

    wsgi = False

    def register(self):
        self.app.bind('TaskConfig', task)
        self.app.bind('TaskTodoDriver', TaskTodoDriver)
        self.app.bind('TaskManager', TaskManager(self.app))

    def boot(self, TaskManager, TaskConfig):
        self.app.bind('Task', TaskManager.driver(TaskConfig.DRIVER))
def show(self, Task):
    Task.method_here()
Service Providers
About Drivers

About Drivers

About Drivers

Introduction

Drivers are simply extensions to features that are managed by the Manager Pattern. If we have a UploadManager then we might also create a UploadDiskDriver and a UploadS3Driver which will be able to upload to both the file system (disk) and Amazon S3. In the future if we have to upload to Microsoft Azure or Google Cloud Storage then we simply create new drivers like UploadAzureDriver and UploadGoogleStorage which are very simple to create. Drivers can be as small as a single method or have dozens of methods. The Manager Pattern makes it dead simple to expand the functionality of a Manager and add capabilities to Masonite's features.

Creating a Driver

Let's go ahead and create a simple driver which is already in the framework called the UploadDiskDriver.

If you are creating a driver it can live wherever you like but if you are creating it for Masonite core then it should live inside masonite/drivers. For our UploadDiskDriver we will create the file: masonite/drivers/UploadDiskDriver.py.

We should make a class that looks something like:

class UploadDiskDriver:
    pass

Simple enough, now we can start coding what our API looks like. In the endgame, we want developers to do something like this from their controllers:

def show(self, Upload):
    Upload.store(request().input('file'))

So we can go ahead and make a store method.

class UploadDiskDriver:

    def store(self, fileitem, location=None):
        pass

Ok great. Now here is the important part. Our Manager for this driver (which is the UploadManager) will resolve the constructor of this driver. This basically means that anything we put in our constructor will be automatically injected into this driver. So for our purposes of this driver, we will need the storage and the application configuration.

class UploadDiskDriver:

    def __init__(self, StorageConfig, Application):
        self.config = StorageConfig
        self.appconfig = Application

    def store(self, fileitem, location=None):
        pass

Now that we have our configuration we need injected into our class, we can go ahead and build out the store() method.:

class UploadDiskDriver:

    def __init__(self, StorageConfig, Application):
        self.config = StorageConfig
        self.appconfig = Application

    def store(self, fileitem, location=None):
        filename = os.path.basename(fileitem.filename)

        if not location:
            location = self.config.DRIVERS['disk']['location']

        location += '/'

        open(location + filename, 'wb').write(fileitem.file.read())

        return location + filename

Ok great! You can see that our store() method simply takes the file and write the contents of the fileitem to the disk.

Using Our Driver

from masonite.provider import ServiceProvider
from masonite.managers.UploadManager import UploadManager
from masonite.drivers.UploadDiskDriver import UploadDiskDriver
from config import storage


class UploadProvider(ServiceProvider):

    wsgi = False

    def register(self):
        self.app.bind('StorageConfig', storage)
        self.app.bind('UploadDiskDriver', UploadDiskDriver)
        self.app.bind('UploadManager', UploadManager(self.app))

    def boot(self, UploadManager, StorageConfig):
        self.app.bind('Upload', UploadManager.driver(StorageConfig.DRIVER))

That's it! Drivers are extremely simple and most drivers you create will be a simple class with a single method or two.

Depending on what type of driver you are making, you may need to inherit from a contract. To ensure this documentation is generalized, we'll leave out contracts for now. Contracts are essentially interfaces that ensure that your driver conforms to all other drivers of the same type. Read more about contracts in the documentation.

Great. If you're confused about how the dependency injection Service Container works then read the documentation.

So now that our driver is created, we can tell our Manager about it. Learn how to create managers under the documentation. Our manager will know of all drivers that are inside the Service Container. We can create a new service provider which we can use to register classes into our container. Here is an example of what the UploadProvider will look like:

Notice how we set our storage configuration in the container, binded our drivers and then binded our Manager. Again, our manager will be able to find all our UploadXDrivers that are loaded into the container. So if we set the DRIVER inside our configuration file to google, our manager will look for a UploadGoogleDriver inside our container. Read more about Managers in the documentation.

Contracts
Service Container
About Managers
About Managers

Masonite AuthHub

Masonite AuthHub

Introduction

Masonite AuthHub brings a centralized and easy to integrate OAuth system to the Masonite Framework. Simply add a few lines of code and the entire OAuth workflow is done for you.

Getting Started

To install Masonite AuthHub just pip install it:

$ pip install authhub

After authhub is installed, we just need to publish it.

Adding The Configuration File

Masonite AuthHub uses the config/services.py configuration file. Conveniently, AuthHub comes with a publish command we can use to create this.

NOTE: Virtual Environment

If you are in a virtual environment, craft publish will not have access to your virtual environment dependencies. In order to fix this, we can add our site packages to our config/packages.py config file

If you are in a virtual environment then go to your config/packages.py file and add your virtual environments site_packages folder to the SITE_PACKAGES list. Your SITE_PACKAGES list may look something like:

SITE_PACKAGES = [
    'venv/lib/python3.6/site-packages'
]

Publishing

Publish AuthHub by running:

$ craft publish authhub

This will create or append to the config/services.py file. If you've published a package that has used the config/services.py file before than you may have to take the contents of the AUTH_PROVIDERS dictionary that was created and condense it down into a single dictionary.

After we have published AuthHub we should get a dictionary that looks like:

AUTH_PROVIDERS = {
    'github': {
        'client': os.environ.get('GITHUB_CLIENT'),
        'secret': os.environ.get('GITHUB_SECRET'),
        'redirect': os.environ.get('GITHUB_REDIRECT'),
        'driver': 'authhub.providers.GitHubDriver.GitHubDriver'
    }
}

Just add the corresponding environment variables to your .env file:

GITHUB_CLIENT=XXX
GITHUB_SECRET=XXX
GITHUB_REDIRECT=http://your-redirect-url/

The GITHUB_REDIRECT url is the url that users will return to after they authenticate. This is likely to match the return URL in your app on the provider you are using. For GitHub, this is called “Authorization callback URL” in your OAuth App’s settings.

Redirecting

AuthHub uses the same syntax for all providers and contains a method of redirecting to the provider as well as a method of getting the response.

To redirect to the provider so you can authorize the user:

return AuthHub(request).driver('github').redirect()

Notice the .driver() method here. This driver will instantiate the driver specified in your configuration setting in the previous step.

If you need to, you can also specify some scopes:

return AuthHub(request).driver('github').scope('repo', 'public_repo').redirect()

Or pass in a state:

return AuthHub(request).driver('github').scope('repo', 'public_repo').state('secret_id').redirect()

The state will be a value returned back after the user has authenticated. This is good for verifying if the user that sent the request is the one that received it.

To get the user response back after the user has authenticated:

return AuthHub(request).driver('github').user()

What this method does is:

  • receives the response back from the provider

  • gets the code from the query string

  • exchanges the code for an access token

  • uses the access token to retrieve and return the user.

Pretty cool, huh?

A complete setup might look something like:

from authhub.authhub import AuthHub

class LoginController(object):
    ''' Class Docstring Description '''

    def __init__(self):
        pass

    def toProvider(self, request):
        return AuthHub(request).driver('github').redirect()

    def fromProvider(self, request):
        user = AuthHub(request).driver('github').user()
        return user['login'] # returns github username

Thats it! Check your platform’s typically response in order to see what is in the user object. It’s a good idea to store the access token in your app/User table and use that token to perform API requests on behest of the user. Many providers like GitHub, Facebook and Twitter all have great Python libraries you can use the token with.

This will allow craft publish to find our dependencies installed on our virtual environment. Read the documentation for more information.

Publishing Packages

Contracts

Contracts

Introduction

Contracts are used when creating drivers to ensure they conform to Masonite requirements. They are a form of interface in other languages where the child class is required to have the minimum number of methods needed for that driver to work. It is a promise to the class that it has the exact methods required.

Contracts are designed to follow the "code to an interface and not an implementation" rule. While this rule is followed, all drivers of the same type are swappable.

Drivers are designed to easily switch the functionality of a specific feature such as switching from file system storage to Amazon S3 storage without changing any code. Because each driver someone creates can technically have whatever methods they want, this creates a technical challenge of having to change any code that uses a driver that doesn't support a specific method. For example a driver that does not have a store method while other drivers do will throw errors when a developer switches drivers.

Contracts ensure that all drivers of a similar type such as upload, queue and mail drivers all contain the same methods. While drivers that inherit from a contract can have more methods than required, they should not.

Getting Started

Contracts are currently used to create drivers and are located in the masonite.contracts namespace. Creating a driver and using a contract looks like:

from masonite.contracts.UploadContract import UploadContract

class UploadGoogleDriver(UploadContract):
    pass

Now this class will constantly throw exceptions until it overrides all the required methods in the class.

Contracts

There are several contracts that are required when creating a driver. If you feel like you need to have a new type of driver for a new feature then you should create a contract first and code to a contract instead of an implementation. Below are the types of contracts available. All contracts correspond to their drivers. So an UploadContract is required to create an upload driver.

BroadcastContract

CacheContract

MailContract

QueueContract

UploadContract

Masonite Triggers

Masonite Triggers

Introduction

Masonite Triggers is a way to add support for triggering classes within various parts of your project. A great use case is to create a class that sends an email and then simple use trigger('sendWelcomeEmail') anywhere in your project.

Installation

At the root of your Masonite project just run:

$ pip install triggers
$ craft publish triggers

Usage

The publish command will create a new configuration file under config/triggers.py where you can register all of your trigger classes. To register your class, just enter an alias you’d like to use for your class as the key and then a string with the full module path to the class.

This configuration file may look something like:

TRIGGERS = {
    'sendWelcomeEMail' : 'app.triggers.SendWelcomeEmail.SendWelcomeEmail'
}

Lets make this class in app/triggers/SendWelcomeEmail.py:

class SendWelcomeEmail(object):

    def __init__(self):
        pass

    def action(self):
        print('Send Welcome Email')

By default, all triggers will fire the action method on your class.

You may now activate that trigger by using the trigger() function:

from triggers.helpers import trigger

trigger('sendWelcomeEmail')

All triggers will default to the action method. You can specify a different method by calling:

trigger('sendWelcomeEmail@premium')

which will call the premium method on the sendWelcomeEmail class. If your functions needs additional parameters you can specify them as extra parameters such as:

trigger('sendWelcomeEmail@premium', user, email)

A method with that trigger will look like:

class SendWelcomeEmail(object):

    def __init__(self):
        pass

    def action(self):
        print('Send Welcome Email')

    def premium(self, user, email)
        pass

That’s it! Triggers are very simple but very powerful.

If publishing does not work, you may be using a virtual environment and may not have the correct site_packages directory added to your config/packages.py file. Read more about this in the documentation.

Publishing Packages

Masonite Clerk

Masonite Clerk

Introduction

Masonite Clerk provides a very expressive and simple syntax to start charging your users with Stripe. In addition to being incredibly easy to setup, Clerk can handle charges, subscriptions, cancellation, subscription swapping, subscription prorating and customer creation. You're going to love it.

Configuration

Pip

First we'll need to install Clerk on our machine. To do this simply run:

$ pip install clerk

Adding The Configuration File

Masonite uses the config/payment.py configuration file. Conveniently, Clerk comes with a publish command we can use to create this.

NOTE: Virtual Environment

If you are in a virtual environment, craft publish will not have access to your virtual environment dependencies. In order to fix this, we can add our site packages to our config/packages.py config file

If you are in a virtual environment then go to your config/packages.py file and add your virtual environments site_packages folder to the SITE_PACKAGES list. Your SITE_PACKAGES list may look something like:

SITE_PACKAGES = [
    'venv/lib/python3.6/site-packages'
]

This will allow craft publish to find our dependencies installed on our virtual environment.

Publishing Masonite Clerk

If you are in a virtual environment it is important you add your virtual environment’s site_packages directory to the config/packages.py file.

We can now run:

$ craft publish clerk

This will create a new configuration file in config/payment.py

API Keys

You'll notice in this new config/payment.py file we have a config setting that looks like:

PROCESSORS = {
    'stripe': {
        'key': os.environ.get('STRIPE_PUBLISHABLE'),
        'secret': os.environ.get('STRIPE_SECRET'),
        'currency': 'usd'
    }
}

Our API keys for key, and secret should reside in our .env file. Just create two entries in your .env file that looks like:

STRIPE_PUBLISHABLE=pk_test_Hghus...
STRIPE_SECRET=sk_test_KIsnsh...

These API keys can be found in your Stripe dashboard.

Database Migrations

We'll assume you want to add billable services to your users so we'll just add a few fields to our users table. Just run:

$ craft migration add_stripe_to_users --table users

Inside this migrations up() method we'll just copy these columns in:

with self.schema.table('users') as table:
    table.string('stripe_id').nullable()
    table.string('card_brand').nullable()
    table.string('card_last_four').nullable()
    table.timestamp('trial_ends_at').nullable()

Next we'll do the same thing but will be creating a subscriptions table.

$ craft migration create_subscriptions_table --create subscriptions

Now just copy and paste these migrations in:

with self.schema.create('subscriptions') as table:
    table.increments('id')
    table.integer('user_id')
    table.string('name')
    table.string('stripe_id')
    table.string('stripe_plan')
    table.integer('quantity')
    table.timestamp('trial_ends_at').nullable()
    table.timestamp('ends_at').nullable()
    table.timestamps()

Now that we've finished our migrations lets migrate them into our database:

$ craft migrate

Billable Model

Lastly we'll add a special class to our users table so we can gain access to a lot of Clerk methods on our model. Let's open our User model and import a new Billable model as well as inherit from it:

from orator import DatabaseManager, Model
from config.database import Model

# New Billable Import
from clerk.Billable import Billable

class User(Model, Billable):

    __fillable__ = ['name', 'email', 'password']

    __auth__ = 'email'

That's it! You're all ready to start charging and subscribing users!

Subscriptions and Charges

NOTE: All references to token are stripe tokens which are sent by the request after a form submission. For testing purposes you can use the 'tok_amex' string which will create a test AMEX card so we don't have to keep submitting forms

To charge a user $1. All amounts are in cents. So below we are charging our user 1000 cents (or $10)

User.find(1).charge(token, 1000)

To create a customer

User.find(1).customer(token)

To subcribe a user to a plan

User.find(1).subscribe('database_plan', 'stripe_plan', token)

To get the actual subscription model from our payment processor. This is great if you want to make some changes to the subscription manually and then .save() it after.

User.find(1).getSubscription()

To cancel the current subscription

User.find(1).cancel()

To get the Customer object from our payment processor. This is great if you want to make changes to the customer object manually and then .save() it

User.find(1).getCustomer()

To delete the user as a customer:

User.find(1).deleteCustomer()

To swap the current processor plan for a new plan. This will prorate the current plan by default.

User.find(1).swap('new_stripe_plan')

If you do not wish to prorate the user. Read more about prorating from the payment processor you are using.

User.find(1).noProrate().swap('new_stripe_plan')

Check if a user is subscribed to a specific stripe plan

User.find(1).subscribedToPlan('stripe_plan')

Check to see if a user is subscribed to any one of the plans specified

User.find(1).subscribedToPlan(['stripe-plan1', 'stripe-plan2'])

To see if the user is currently subscribed (to any plan)

User.find(1).subscribed()

To see if a user is subscribed to a specific plan (a local plan, not a stripe plan)

User.find(1).subscribed('main-plan')

To see if a user is subscribed to any of the plans specified (local plans, not a stripe plans)

User.find(1).subscribed(['main-plan', 'second-plan'])