Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
A new version of masonite is released. You can view the 2.1 Documentation Here
The modern and developer centric Python web framework that strives for an actual batteries included developer tool with a lot of out of the box functionality with an extremely extendable architecture. Masonite is perfect for beginner developers getting into their first web applications as well as experienced devs that need to utilize the full potential of Masonite to get their applications done.
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. Use it for your next SaaS! Try it once and you’ll fall in love.
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.
Extremely extendable.
These, among many other features, are all shipped out of the box and ready to go. Use what you need when you need it.
In order to use Masonite, you’ll need:
Python 3.4+
Pip3
All commands of python and pip in this documentation is assuming they are pointing to the corresponding Python 3 versions. If you are having issues with any installation steps just be sure the commands are for Python 3.4+ and not 2.7 or below.
NOTE: Masonite does not support the Anaconda virtual environment system. In order for the craft command to work, something you will be using often, Masonite needs to be able to locate the Masonite package even in a virtual environment. If you follow the installation steps here and use Python 3's builtin virtualenv package (python3 -m venv venv
) then this will work best. If you would like to add Anaconda support to Masonite then feel free to open an issue in GitHub :)
If you are running on a Linux flavor, you’ll need the Python dev package and the libssl package. You can download these packages by running:
Or you may need to specify your python3.x-dev
version:
Be sure to join the Slack Channel for help or guidance.
Masonite excels at being simple to install and get going. We use a simple command line tool that will become your best friend. You’ll never want to develop again without it. We call them craft
commands.
We can download our craft
command line tool by just running:
If you are having installation issues, be sure to read the Known Installation Issues documentation.
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:
The python
command here is utilizing Python 3. Your machine may run Python 2 (typically 2.7) by default for UNIX machines. You may set an alias on your machine for Python 3 or simply run python3
anytime you see the python
command.
For example, you would run python3 -m venv venv
instead of python -m venv venv
Now lets install our dependencies. We can do this simply by using a craft
command:
This command is just a wrapper around the pip
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:
After it’s done we can just run the server by using another craft
command:
You can also run the server in auto-reload mode which will rerun the server when file changes are detected:
Congratulations! You’ve setup your first Masonite project! Keep going to learn more about how to use Masonite to build your applications.
You can also add a auto reloading option to the serve command by running craft serve -r
which will reload the server whenever you save a python file.
You can learn more about craft by reading The Craft Command documentation or continue on to learning about how to create web application by first reading the Routing documentation
Masonite has romantic versioning instead of semantic versioning. Because of this, all minor releases (2.0.x) will contain bug fixes and fully backwards compatible feature releases. Be sure to always keep your application up to date with the latest minor release to get the full benefit of Masonite's romantic versioning.
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.BUGFIX
.
This means that a framework version of 1.3.20 may have breaking changes with version 1.4.0. Masonite uses a 6 month major release cycle in order to maintain it's state as a modern Python web framework. Each release is a solid and stable release and upgrading typically takes minimal time.
The Masonite main repository (the MasoniteFramework/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.
Because MasoniteFramework/masonite
does not require major updates, we can follow RomVer nicely and keep the versioning number artificially lower. Any major updates to this repository will likely just be file structure changes which should rarely happen unless there are major architectural changes.
TL;DR: Minor release every 2 weeks. Major release every 6 months. Beta releases every 1 month starting 4 months out from major release (i.e: September, October, November is beta 1, 2 and 3 and then feature freeze for beta 3). Then the major release on the 4th month (December). Similar concept for June releases.
Masonite is currently on a 6 month major release cycle. This means that once six months will be a new 2.x release.
Masonite is currently on a 6 month major release cycle. This means that once six months will be a new 2.x release.
Releases are planned to be upgradable from the previous release in 30 minutes or less. If they break that requirement then they should be considered for the next Paradigm release (the x.0.0
release)
Masonite is currently on a 6 month release cycle and is made up of three different repositories:
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 craft repository where the craft command tool is located.
When developing new releases there will be 3 beta releases before the final release. So for example if Masonite 2.1 is being released in December, there will be a beta 1 release in September, beta 2 in October, beta 3 in November and then the final 2.1 release in December.
These releases will be called something like:
v2.1.0b1
v2.1.0b2
v2.1.0b3
v2.1.0
The core repository is uploaded to PyPi under the new release number. At this time, everyone could theoretically install the package. Once core is released, craft is updated for any minor changes it may require. Once these two repositories are completed, the masonite repository is updated and finally released. Once this repo is released to the latest version, all future projects will default to the latest version of Masonite.
The third beta release will be a complete feature freeze and not introduce any new features.
Sometimes we might come out with a beta release and something is broke on it that was not caught in tests and we need to "hotfix" them. These will be called "post" releases since they will append a postN
to the beta release and will be numbered like so:
v2.1.0b1.post1
A full release structure from 2.0 to 2.1 might be something like:
v2.0.16 - Normal minor release
v2.1.0b1 - First beta release
v2.1.0b1.post1 - Bugfix on beta 1 release
v2.1.0b2 - Second beta release
v2.1.0b2.post1 - Bugfix on beta 2 release
v2.1.0b2.post2 - Bugfix on beta 2 release
v2.1.0b3 - Third beta release
v2.1.0 - Final release
After that we will bump the version of Masonite in the documentation and verify and update any documentation that is not up to date or standard.
Whenever the MasoniteFramework/craft
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.
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 The Craft Command documentation. The craft new
command will download a zip of the latest release of Masonite, unzip it and rename the folder. Once the next release for this repository is ready, it will be released but marked as a Pre-release
and therefore will not be installable by the default craft new
command.
This is so developers and maintainers will be able to test the new pre release with their applications. Once all QA tests have passed, it will be marked as a normal release and therefore all new applications created from there on out will be the new release.
Developers will still have the option of doing something like: craft new project_name --version 1.6
and installing that version of Masonite.
Once all three repositories are ready for release, they will all be released on GitHub under the respective new version numbers.
You may want to test new beta releases to help with any existing bugs. Upgrade guides will be release between the beta 3 release and the final release so it might not be possible to upgrade your existing application within a beta 1 or beta 2 release.
You may still create new applications though since those should work pretty much the same as the previous release in terms of installation. Here are the installation instructions to test new beta releases:
You'll need to first craft new the project but use the develop branch:
You may need to update this file as well to change the masonite version to the latest beta version. You can find the latest beta version on GitHub.
Now we just need to install the application like normal. Here we will first create and activate the virtual environment:
If you're on Windows you'll need to activate the virtual environment with the ./venv/Scripts/activate
command.
Great! You now have the latest release of Masonite. Documentation may or may not be up to date. Check the latest version number in the documentation
We sincerely thank all individuals who have chosen to become sponsors! You are truly making Masonite a fantastic community!
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.
Previously when 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.
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.
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.
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:
As well as support for Amazon S3 by setting the DRIVER
to s3
.
These helper functions are added functions to the builtin Python functions which can be used by simply calling them as usual:
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 its own service provider:
You can now specify anything that is in the container in your middleware constructor and it will be resolved automatically from the container
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:
By default, masonite will look for routes in the app/http/controllers
namespace but you can change this for individual routes:
This will look for the controller in the thirdparty.routes
module.
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.
The framework has three main parts.
This MasoniteFramework/masonite
repository is the main repository that will install when creating new projects using the craft new
command. Not much development will be done in this repository and won't be changed unless new releases of Masonite require changes in the default installation project.
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
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
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.
This repository has a barebones skeleton of a sample project in order to aid in testing all the features of Masonite against a real project. If you install this as editable by passing the --editable
flag then this may break your project because it will override the modules in this package with your application modules.
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 craft (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 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)
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.
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 for several minutes.
Ensure any changes are well commented and any configuration files that are added have a flagpole comment on the variables it's setting.
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.
You must add unit testing for any changes made. Of the three repositories listed above, only the craft
and core
repos require unit testing.
The PR must pass the Travis CI build. The Pull Request can be merged in once you have a successful review from two other collaborators, or the feature maintainer for your specific feature improvement or the repo owner.
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.
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
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.
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.
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.
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 can be created with the new craft job
command. See the documentation for more information.
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 craft
or for the main Masonite repo.
This Code of Conduct is adapted from the , version 1.4, available at
Masonite 1.6 brings mostly minor changes to the surface layer of Masonite. This release brings a lot of improvements to the engine of Masonite and sets up the framework for the release of 2.0.
Previously, all cookies were set with an HttpOnly flag when setting cookies. This change came after reading several articles about how cookies can be read from Javascript libraries, which is fine, unless those Javascript libraries have been compromised which could lead to a malicious hacker sending your domain name and session cookies to a third party. There is no the ability to turn the HttpOnly flag off when setting cookies by creating cookies like:
Because craft is it's own tool essentially and it needs to work across Masonite versions, all commands have been moved into the Masonite repository itself. Now each version of Masonite maintains it's own commands. The new craft version is 2.0
Before, you had to use the Manager class associated with a driver to switch a driver. For example:
Now you can switch drivers from the driver itself:
This version has been fine tuned for adding packages to Masonite. This version will come along with a new Masonite Billing package. The development of Masonite Billing has discovered some rough spots in package integrations. One of these rough spots were adding controllers that were not in the project. For example, Masonite Billing allows adding a controller that handles incoming Stripe webhooks. Although this was possible before this release, Masonite 1.6 has added a new syntax:
Notice the new forward slash in the beginning where the string controller goes.
Previously, controllers were created as they were specified. For example:
created a DashboardController. Now the "Controller" part of the controller is appended by default for you. Now we can just specify:
to create our DashboardController. You may was to actually just create a controller called Dashboard. We can do this by specifying a flag:
short for "exact"
It's also really good practice to create 1 controller per "action type." For example we might have a BlogController
and a PostController
. It's easy to not be sure what action should be in what controllers or what to name your actions. Now you can create a "Resource Controller" which will give you a list of actions such as show, store
, create
, update
etc etc. If what you want to do does not fit with an action you have then you may want to consider making another controller (such as an AuthorController
)
You can now create these Resource Controllers like:
Just like the global controllers, some packages may require you to add a view that is located in their package (like the new exception debug view in 1.6) so you may now add views in different namespaces:
This will get a template that is located in the masonite package itself.
You can now group routes based on a specific string prefix. This will now look like:
which will compile down into /dashboard/user
and /dashboard/user/1
The container was one of the first features coded in the 1.x release line. For Masonite 1.6 we have revisited how the container resolves objects. Before this release you had to put all annotation classes in the back of the parameter list:
If we put the annotation in the beginning it would have thrown an error because of how the container resolved.
Now we can put them in any order and the container will grab each one and resolve it.
This will now work when previously it did not.
The container will now resolve instances of classes as well. It's a common paradigm to "code to an interface and not an implementation." Because of this paradigm, Masonite comes with contracts that act as interfaces but in addition to this, we can also resolve instances of classes.
For example, all Upload drivers inherit the UploadContract contract so we can simply resolve the UploadContract which will return an Upload Driver:
Notice here that we annotated an UploadContract but got back the actual upload driver.
You can now search the container and "collect" objects from it by key using the new collect method:
which will find all keys in the container such as SentryExceptionHook and SentryWebHook and make a new dictionary out of them.
A complaint a few developers pointed out was that Masonite has too many dependencies. Masonite added Pusher, Ably and Boto3 packages by default which added a bit of overhead, especially if developers have no intentions on real time event broadcasting (which most applications probably won't). These dependencies have now been removed and will throw an exception if they are used without the required dependencies.
Masonite 1.6 + will slowly be rolling out various framework hooks. These hooks will allow developers and third party packages to integrate into various events that are fired throughout the framework. Currently there is the abilitity to tie into the exception hook which will call any objects loaded into the container whenever an exception is hit. This is great if you want to add things like Sentry into your project. Other hooks will be implemented such as View, Mail and Upload Hooks.
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 Contributing Guide and the How To Contribute documentation.
If you are upgrading from Masonite 1.3 then please read the Masonite 1.3 to 1.4 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 About Drivers 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.
Masonite now has a built in caching class that you can use to either cache forever or cache for a specific amount of time.
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.
We have also updated the code to closely conform to PEP 8 standards.
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.
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.
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.
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.
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.
There were two unused imports in the models that Masonite created. These have been removed completely.
There are no known Masonite specific issues known and if there are then there should be an issue open for them on GitHub. With that being said, some users may experience some difficulties with installing Masonite simply because their computer environment is not the norm, they have never setup Python and may have configured it incorrectly or they have not used Python in a while and have an old version.
Before you get started reading through this FAQ make sure you have:
Python 3.4+
Pip3
Ensure you are installing masonite-cli with pip3
and not pip
.
You are likely running this command on a UNIX based machine like Mac or Linux. In that case you should either run it again with a sudo command or a user command flag:
or
If you ran:
and then run:
and get something like:
then try closing your terminal and reopening it. If that doesn't work then you may be running a pip version connecting to Python 2.7. Try uninstalling it and reinstalling it using pip3:
If that does not work then you may have to run sudo:
You may get a strange error like:
The simple fix may just be to run:
If that doesn't work we can just go back to the lower idna version:
If that does not fix the issue then continue reading.
If the above fix did not work then this likely means you installed masonite-cli using the Python 2.7 pip command. Out of the box, all Mac and Linux based machines have Python 2.7. If you run:
you should get a return value of:
But if you run:
you should get a return value of:
Now pip commands are similar:
Notice here we are using 2 different Python installations.
So if you are getting this error you should uninstall masonite-cli from pip and reinstall it using pip3:
You may have to run sudo to remove and install it and you may need to close your terminal to get it work if you are using a UNIX machine.
If you installed everything successfully and running:
Shows an error that it can't be found then try closing your terminal and opening it again. This should refresh any commands that were recently installed
If you still have errors and on a UNIX based machine try running:
You likely ran:
and hit this weird snag that throws this ambiguous error. You might think this is because of a Python version issue but craft is designed to work on Python 2.7 and 3.4+ (although 2.7 and not thoroughly tested) and you're years of Python experience would make you right but this is special. If you are getting this error then that means you are likely on a UNIX machine, Mac right?
The problem is that your machine does not have sufficient permissions to access these external calls from the command line because your machine does not have permission to do so. You will have to give you machine the command to do so by running:
or whatever your Python 3 version is in the middle. Now try running:
and it should work great!
Masonite 1.5 is focused on a few bug fixes and changes to several core classes in order to expand on the support of third party package integration.
Masonite 1.5 is releasing also with a new official package for adding RESTful API's to your project. This package used API Resources which are classes that can add a plethora of capabilities to your API endpoints. You can read more about it at the documentation.
Masonite 1.5 also adds additional support HTTP methods like PUT
, PATCH
and DELETE
. More information about these new routes can be found under the documentation
Nearly all dependencies have been moved to the core Masonite package. The only thing inside the project that is installed using craft new
is the WSGI server (which is waitress by default) and Masonite itself. This will improve the ability to change and update dependencies.
HTML forms only support GET and POST so there is no the ability to add any other HTTP methods like PUT
and PATCH
which will change the actual request method on submission. You can read more about this in the documentation.
In Masonite 1.4 and below was the Api()
route which added some very basic API endpoints. All references to API's have been removed from core and added to the new Masonite Entry official package.
If you would like to use API's you will have to use the Masonite Entry package instead.
You can now add data to sessions using the new Sessions feature which comes with a memory and cookie driver for storing data.
In previous versions, Masonite has not been able to fetch the site packages directory if you were in a virtual environment because virtual environment directories are dynamically named depending on who created it. We have found a way to detect the virtual environment and the site packages directory so now there is no need to add the site packages directory manually to the packages configuration file
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
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.
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.
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.
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:
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
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:
Lastly, put that middleware into the HTTP_MIDDLEWARE
list inside config/middleware.py
like so:
should now be:
with this change
Not much has changed in the actual project structure of Masonite 1.6 so we just need to make some minor changes to our existing 1.5 project
We just have to change our Masonite dependency version in this file:
Masonite 1.6 now wraps the majority of the application in a try and catch block so we can add exception handling such as the new debug view and other exception features down the road such as Sentry and other error logging.
In the middle of the file (line 45 if you have not made changes to this file) we can simply wrap the application:
This will also display an exception view whenever an exception is it.
That's all the changes we have to make for our project.
Masonite 2 brings an incredible new release to the Masonite family. This release brings a lot of new features to Masonite to include new status codes, database seeding, built in cron scheduling, controller constructor resolving, auto-reloading server, a few new internal ways that Masonite handles things, speed improvements to some code elements and so much more. We think developers will be extremely happy with this release.
Upgrading from Masonite 1.6 to Masonite 2.0 shouldn't take very long. On an average sized project, this upgrade should take around 30 minutes. We'll walk you through the changes you have to make to your current project and explain the reasoning behind it.
Checkout the
Controller constructors are now resolved by the container so this removed some redundancy within your code and any duplicated auto resolving can now be directly in your constructor:
Read more in the documentation.
There is a new command that starts a Python shell and imports the container for you already. Test it out to verify that objects are loaded into your container correctly. It's a great debugging tool.
Masonite 2 ships with an awesome little helper command that allows you to see all the routes in your application
A huge update to Masonite is the new --reload
flag on the serve command. Now the server will automatically restart when it detects a file change. You can use the -r
flag as a shorthand:
An incredible new feature is autoloading support. You can now list directories in the new AUTOLOAD
constant in your config/application.py
file and it will automatically load all classes into the container. This is great for loading command and models into the container when the server starts up.
You can also use this class as a standalone class in your own service providers.
Updated all libraries to the latest version with the exception of the Pendulum library which latest version is a breaking change and therefore was left out. The breaking change would not be worth it to add the complexity of upgrading so you may upgrade on a per project basis.
Previously you had to import classes like:
Now you can simply specify:
Because of this change we no longer need the same duplicated class names in the PROVIDERS list either.
Removed the need for the redirection provider completely. You need to remove this from your PROVIDERS
list.
Renamed Request.redirectTo
to Request.redirect_to
Also removed the .send() method and moved the dictionary into a parameter:
Added a new Request.only method to fetch only specific inputs needed.
Added a new Request.get_request_method()
method to the Request
class.
You can now completely remove fetching of any inputs that Masonite handles internally such as __token and __method when fetching any inputs. This is also great for building third party libraries:
Because of the changes to internal framework variables, there are several changes to the CSRF middleware that comes in every application of Masonite.
Added a new default package to Masonite that allows scheduling recurring tasks:
It's important during development that you have the ability to seed your database with dummy data. This will improve team development with Masonite to get everyones database setup accordingly.
Now all templates have a new static function in them to improve rendering of static assets
You can use the password helper to hash passwords more simply than using straight bcrypt:
You can now specify which location in your drivers you want to upload to using a new dot notation:
This will use the directory stored in:
Masonite 2 removes the bland error codes such as 404 and 500 errors and replaces them with a cleaner view. This also allows you to add custom error pages.
Providers are now explicitly imported at the top of the file and added to your PROVIDERS list which is now located in config/providers.py
. This completely removes the need for string providers and boosts the performance of the application sustantially
This is currently unreleased and is in a Beta 3 release. There will be the final release of 2.1 in December.
Learn more about releases in the documentation.
Masonite 2.1 introduces a few new changes that are designed to correct course for the 2.x family and ensure we can go far into the 2.x family without having to make huge breaking changes. It was questionable whether we should break from the 2.x family and start a new 3.x line. The biggest question was removing (actually disabling) the ability to resolve parameters and go with the more favorable annotation resolving. That could have made Masonite a 3.x line but we have ultimately decided to go with the 2.1 as a course correction. Below you will find all changes that went into making 2.1 awesome. Nearly all of these changes are breaking changes.
These changes are subject to change before the final release.
It is much easier to contribute to Masonite now since nearly classes have awesome docstrings explaining what they do, their dependencies and what they return.
We have completely removed parameter resolving. We can no longer resolve like this:
in favor of the more explicit:
This is a bit of a big change and will be most of the time spent on refactoring your application to upgrade to Masonite 2.1. If you already used the more explicit version then you won't have to worry about this change. It is still possible to resolve parameters by passing that keyword argument to your container to activate that feature:
This should help with upgrading from 2.0 to 2.1 until you have refactored your application. Then you should deactivate this keyword argument so you can be in line with future 2.x releases.
You can choose to keep it activated if that is how you want to create applications but it won't be officially supported by packages, future releases or in the documentation.
All middleware are now classes:
this is different from the previous string based middleware
Previously when getting an incoming JSON response, we had to get the values via the payload input like so:
which was kind of strange in hindsight. Now we can just straight up use the input:
Again this is only a change for incoming JSON responses. Normal form inputs remain the same.
Previously we had a facades module but it was being unused and we didn't see a future for this module so we moved the only class in this module to it's own class. All instances of:
now become:
We also noticed that for some reason we were parsing parameters before we found routes but we only ever needed those parameters inside our routes so we were parsing them whether we found a route or not. We moved the parsing of parameters into the if statement that executes when a route is found.
When we say "parsing route parameters" we mean the logic required to parse this:
into a usable form to use on the request class this:
This provider has been completely removed for the more recommended ResponseMiddleware which will need to be added to your HTTP middleware list:
We also noticed that for some reason we were parsing parameters before we found routes but we only ever needed those parameters inside our routes so we were parsing them whether we found a route or not. We moved the parsing of parameters into the if statement that executes when a route is found.
When we say "parsing route parameters" we mean the logic required to parse this:
into a usable form to use on the request class this:
You can now optionally use .
instead of /
in your views:
We moved the CSRF middleware completely into the core framework and allow developers to extend from it now. This will allow us to fix any security bugs that are apart of the CSRF feature.
You may see this pattern a lot in the future which is only extending classes from the core framework so we can hot fix things much better.
Masonite now has a plethora of docstrings on each and every class by default to really give the developer an understanding about what each default class is actually doing and what it is dependent on.
Masonite is also much more PEP 8 compliant. We removed all instances of triple single quotes: '''
for the more preferred and PEP 8 compliant double quotes """
for docstrings.
We also cleaned a lot of the classes generated by the auth command since those were pretty ugly.
We also removed all instances of helper functions by default since it was confusing developers and was throwing red squiggly marks for text editors. They are still available to be used but they will not be known to developers unless they discover them in the documentation. Now all default code explicitly resolves via the container and helper functions can be used on the developers own terms.
Helper functions are still available but you will need to use them on your own terms.
Now every application has a basic seeding structure setup which is the same as if running the craft seed
command. This is to promote more use of this awesome feature which can be used in migration files for quick seeding of databases for development.
We were previously not able to import code into our migration files or database seeders because the command line tool would not pick up our current working directory to import classes into. Now the migrations module and seeds module have 3 lines of code:
this helpers when running the command line to import code into these modules.
In development you would see a message like:
When you hit a route in development mode. Well you would also hit it in production mode too since that was never turned off. Although this is likely fine, it would slow down the framework significantly under load since it takes a bit of resources to print something that didn't need to be printed. This enables a bit of a performance boost.
This command gets the statuses of all migrations in all directories. To include third party migration directories that are added to your project.
simple
container bindingsSometimes you do not need to bind an object to any key, you just want the object in the container. For this you can now do simple
bindings like this:
This new mail helper can be used globally which points to the default mail driver:
|safe
filters on built in template helpers.We no longer need to do:
We can now simply do:
Previously we had to specify the status code as a string:
in order for these to be used properly. Now we can just specify the status code:
There is quite a bit of things to remember when binding various things into the container. For example when binding commands, the key needs to be postfixed with Command
like ModelCommand
. Now we can do things like:
Along with this there are several other methods to help you bind things into the container without having to remember all the special rules involved, if any.
We now have View Routes on all instances of the normal HTTP classes:
We previously used this method on the Cache class like so:
Now we removed the cache_
prefix and it is just:
We can now use the .without()
method on the request class which returns all inputs except the ones specified:
Previously the port was missing from the database configuration settings. This was fine when using the default connection but did not work unless added to the config.
Instead of doing something like:
We can now use a dictionary:
We can now specify a route with multiple HTTP methods. This can be done like so:
Core can now emit events that can be listened to through the container.
Now you can setup a way to send email verifications into your user signup workflow simply but inherting a class to your User model.
Now all redirections set the status code implicitly instead of explicitly needing to set them.
Now you can use craft middleware MiddlewareName
in order to scaffold middleware like other classes.
All views can optionally use dot notation instead of foward slashes:
is the same as:
We can now do container swapping which is swapping out a class when it is resolved. In other words we may want to change what objects are returned when certain objects are resolved. These objects do not have to be in the container in the first place.
You can now use a env
function to automatically type cast your environment variables turning a numeric into an int:
You can now resolve from a container with a parameter list in addition to custom parameters.
In addition to all the awesome things that craft auth
generates, we now generate password reset views and controllers as well for you
Fixed an issue where custom route compilers was not working well with request parameters
All new 2.1 projects have a seeder setup so you can quickly make some mock users to start off your application. All users have a randomly generated email and the password of "secret".
You can run seeders by running:
When setting headers we had to set the http_prefix to None more times then not. So it is set by default.
This:
can change to:
Originally the code:
would return None
if there was no header. Now this returns a blank string.
There is now an up and down command so you can put that in your application in a maintenance state via craft commands:
There is also a new MaintenanceModeMiddleware
:
Masonite 1.5 doesn't bring many file changes to Masonite so this upgrade is fairly straight forward and should take less than 10 minutes.
All requirements are now gone with the exception of the WSGI server (waitress
) and the Masonite dependency. You should remove all dependencies and only put:
If you have added your site packages directory to our packages configuration file, you can now remove this because Craft commands can now detect your site packages directory in your virtual environment.
Remove the masonite.providers.ApiProvider.ApiProvider
from the PROVIDERS
list as this has been removed completely in 1.5
If you are using the Api()
route inside routes/api.py
for API endpoints then remove this as well. You will need to implement API endpoints using the new Official package instead.
You'll also have to add a new RESOURCES = []
line to your routes/api.py
file for the new Masonite Entry package if you choose to use it.
This release works with the new craft command release. Upgrade to version masonite-cli / 1.1+
. <1.1
will only work with Masonite 1.4 and below.
Simply run:
You may have to run sudo if you are using a UNIX machine.
Masonite 1.5 now has sessions that can be used to hold temporary data. It comes with the cookie and memory drivers. Memory stores all data in a class which is lost when the server restarts and the cookie driver sets cookies in the browser.
There is a new config/session.py
file you can copy and paste:
As well as add the SessionProvider
inside your PROVIDERS
list just below the AppProvider
:
That's it! You have officially upgrades to Masonite 1.5
You can now use functions for routes instead of the classes. These new functions are just wrappers around the classes itself. Read more about this under the documentation.
You can now get and set any header information using the new Request.header
method. This also allows third party packages to manipulate header information. Read more about this in the documentation.
You can now delete cookies using the delete_cookie
method as well as set expiration dates for them. See the documentation for more information.
The Cache driver now has an update method which can update a cache value by key. This is useful if you want to change a key value or increment it. Storing a cache file also now auto creates that directory. Read more about this in the documentation.
Craft commands have been built from the ground up with the cleo package. It's an excellent package that is built around the extendability of commands by using primarily classes (instead of decorator functions). Read more under documentation
It is now possible to add craft commands to craft. You can read more about how under documentation
You can now add more migration directories by adding it to the container with a key ending in MigrationDirectory
. This will add the directory to the list of directory that run when migrate commands are ran. You can read more about this in the documentation.
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:
Read for any futher changes you may want or have to make to your code base.
Read more in documentation.
Read more in documentation.
Read more in Introduction documentation.
Read more in documentation.
Read more about changing duplicated class names under the documentation.
Read more in the documentation.
Read more in documentation.
Read more in documentation.
Read more in documentation.
Be sure to read the changes in the .
Read about Masonite Scheduler under the documentation.
Read more in the documentation.
Read more in the documentation.
Read more in the documentation.
Read more in the documentation.
Read more in the documentation.
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:
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:
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:
It’s important here to recognize that we didn't initialize the controller or the method, we did not actually call the method. This is so Masonite can pass parameters into the constructor and method when it executes the route, typically through auto resolving dependency injection.
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.
There are several HTTP verbs you can use for routes:
If the syntax is a bit cumbersome, you just want to make it shorter or you like using shorthand helper functions, then you can also use these:
These return instances of their respective classes so you can append on to them:
Most developers choose to use these instead of the classes.
Some routes may be very similar. We may have a group of routes under the same domain, uses the same middleware or even start with the same prefixes. In these instances we should group our routes together so they are more DRY and maintainable.
We can add route groups like so:
This alone is great to group routes together that are similar but in addition to this we can add specific attributes to the entire group like adding middleware:
In this instance we are adding these 2 middleware to all of the routes inside the group. We have access to a couple of different methods. Feel free to use some or all of these options:
The prefix
parameter will prefix that URL to all routes in the group as well as the name
parameter. The code above will create routes like /dashboard/url1
with the name of post.create
. As well as adding the domain and middleware to the routes.
All of the options in a route group are named parameters so if you think adding a groups attribute at the end is weird you can specify them in the beginning and add the routes
parameter:
Even more awesome is the ability to nest route groups:
This will go to each layer and generate a route list essentially from the inside out. For a real world example we refactor routes from this:
into this:
This will likely be the most common way to build routes for your application.
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:
It is good convention to name your routes since route URI's can change but the name should always stay the same.
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:
This middleware will execute either before or after the route is executed depending on the middleware.
Read more about how to use and create middleware in the Middleware documentation.
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:
Controllers are defaulted to the app/http/controllers
directory but you may wish to completely change the directory for a certain route. We can use a forward slash in the beginning of the controller namespace:
This can enable us to use controllers in third party packages.
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:
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:
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.
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:
This will match /dashboard/joseph
and not /dashboard/128372
. Currently only the integer and string types are supported.
These are called "Route Compilers" because they compile the route differently depending on what is specified. If you specify :int
or :integer
it will compile to a different regex than if you specified :string
.
We can add route compilers to our project by specifying them in a Service Provider.
Make sure you add them in a Service Provider where wsgi
is False
. We can add them on the Route class from the container using the compile
method. A completed example might look something like this:
We just need to call the compile()
method on the Route
class and make sure we specify a regex string by preceding an r
to the beginning of the string.
Your regex should be encapsulated in a group. If you are not familiar with regex, this basically just means that your regex pattern should be inside parenthesis like the example above.
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
.
Out of the box this feature will not work and is turned off by default. We will need to add a call on the Request class in order to activate subdomains. We can do this in the boot method of one of our Service Providers that has wsgi=False:
To use subdomains we can use the .domain()
method on our routes like so:
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.
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:
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 work in similar ways.
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. In other words, controller methods may utilize class attributes or private methods to break up logic. They provide a lot of flexibility.
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:
When we run this command we now have a new class in app/http/controllers/DashboardController.py
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.
Notice that we passed in Dashboard
but created a DashboardController
. Masonite will always assume you want to append Controller
to the end.
Remember that Masonite will automatically append Controller to the end of all controllers. If you want to create the exact name of the controller then you can pass a -e
or --exact
flag.
or
This will create a Dashboard
controller located in app/http/controllers/Dashboard.py
Resource controllers are controllers that have basic CRUD / resource style methods to them such as create, update, show, store etc. We can create a resource controller by running:
or
this will create a controller that looks like:
Controller methods are very similar to function based views in a Django application. Our controller methods at a minimum should look like:
All controller methods must start with the self parameter. The self
parameter is the normal python self
object which is just an instance of the current object as usual. Nothing special here.
All controller methods and constructors are resolved by the container so you may also retrieve additional objects from the container by specifying them as a parameter in the method:
or by specifying them in the constructor:
If you need a class in multiple controller methods then it is recommended to put it into the contructor in order to keep the controller DRY.
This might look magical to you so be sure to read about the IOC container in the Service Container documentation.
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.
Read about how to create and use views by reading the Views documentation
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, a thriving community and have as little bugs as possible. Below I will explain how to contribute to this project in different ways both including and excluding code contributions.
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.
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 Controllers and Routing work and read the Architectural Concepts documentation starting with the Request Lifecycle, then the Service Providers and finally the Service Container.
It would also be good to read about the Release Cycle to get familiar with how Masonite does releases (SemVer and RomVer).
Feature Maintainers are people who are in charge of specific features (such as Caching or Creating Packages). These developers will be in charge of reviewing PR's and merging them into the development branch and also have direct contact with the repository owner to discuss.
Feature maintainers must already have significant contributions to the development of the repository they are trying to be a Feature Maintainer for. Although they do not have to be contributors to the actual feature they plan to maintain.
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!
The Masonite pip packages 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 Medium or YouTube. 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.
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.
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 Gitbook.com 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 GitHub.com issues page.
Look at the issues page on GitHub.com 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.
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.
Another idea is to use Masonite to build applications such as a screencast website like LaraCasts.com 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 by 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.
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.
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 Contributing Guide documentation.
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.
Every framework needs great packages and we as the maintainers of Masonite can only do so much with coming out with great packages and maintaining the framework at the same time. We look forward to our community coming out with awesome additions to the Masonite ecosystem. If you have any issues then be sure to open in the gitter chatroom on the Github homepage.
Masonite 2.1 is a fantastic release. It works out a lot of the kinks that were in 2.0 as well as brings several new syntactically good looking code generation
This guide just shows the major changes between version to get your application working on 2.1. You should see the What's New in 2.1 documentation to upgrade smaller parts of your code that are likely to be smaller quality of life improvements.
For 2.1 you will need masonite-cli>=2.1.0
.
Make sure you run:
Middleware has been changed to classes so instead of doing this in your config/middleware.py
file:
You will now import it directly:
This is likely the biggest change in 2.0. Before 2.1 you were able to fetch by key when resolving by doing something like:
We have removed this by default and now you much explicitly import your classes in order to interact with the container resolving:
If you truly do not like this change you can modify your container on a per project basis by adding this to your container constructor in wsgi.py
:
Just know this is not recommended and Masonite may or may not remove this feature entirely at some point in the future.
Previously we were able to do something like this:
Since we never actually created a class from this and you were not able to explicitly resolve this, we utilized the new container swapping in order to swap a class out for this container binding.
All instances above should be changed to:
Don't forgot to also do your boot
methods on your Service Providers as well:
As well as all your middleware and custom code:
You may have classes you binded personally to the container like this:
To get this in line for 2.1 you will need to use Container Swapping in order to be able to resolve this. This is actually an awesome feature.
First go to your provider where you binded it to the container:
and add a container swap right below it by swapping it with a class:
now you can use that class to resolve:
Completely removed the masonite.facades
module and put the only class (the Auth
class) in the masonite.auth
module.
So all instances of:
need to be changed to:
The StartResponseProvider
was not doing anything crazy and it could be achieved with a simple middleware. This speeds up Masonite slightly by offsetting where the response preparing takes place.
Simply remove the StartResponseProvider
from your PROVIDERS
list:
As well as put the new middleware in the HTTP middleware
JSON payloads have been moved into the normal input handling. In 2.1 you had to fetch incoming JSON payloads like this:
So now all instances of the above can be used normally:
CSRF middleware now lives in core and allows you to override some methods or interact with the middleware with class attributes:
Replace your current CSRF Middleware with this new one:
If you made changes to the middleware to prevent middleware from being ran on every request you can now set that as a class attribute:
This also allows any security issues found with CSRF to be handled on all projects quickly instead of everyone having to patch their applications individually.
In migrations (and seeds) you will need to put this import inside a __init__.py
file in order to allow models to be imported into them
There was a slight change in the bootstrap/start.py file
around line 60
.
This line:
Needs to be changed to:
You no longer should bind directly to the Response
key in the container. You should use the new Response object.
All instances of:
should now be:
and any instance of:
should be changed to:
Restructuring some sample code would be changing this:
to this:
The Cache.cache_exists()
has been changed to just Cache.exists()
. You will need to make changes accordingly:
That is all the main changes in 2.1. Go ahead and run your server and you should be good to go. For a more up to date list on small improvements that you can make in your application be sure to checkout the Whats New in 2.1 documentation article.
Although not a critical upgrade, it would be a good idea to replace all instances of retrieval of environment variables with the new masonite.env
function.
Change all instances of this:
with the new env
function:
What this will do is actually type cast accordingly. If you pass a numeric value it will cast it to an int and if you want a boolean if will cast True
, true
, False
, false
to booleans like this:
if you don't want to cast the value you can set the cast
parameter to False
We removed the store_prepend()
method on the upload drivers for the filename
keyword arg on the store method.
So this:
now becomes:
Masonite 2 brings an incredible new release to the Masonite family. This release brings a lot of new features to Masonite to include new status codes, database seeding, built in cron scheduling, controller constructor resolving, auto-reloading server, a few new internal ways that Masonite handles things, speed improvements to some code elements and so much more. We think developers will be extremely happy with this release.
Upgrading from Masonite 1.6 to Masonite 2.0 shouldn't take very long although it does have the largest amount of changes in a single release. On an average sized project, this upgrade should take around 30 minutes. We'll walk you through the changes you have to make to your current project and explain the reasoning behind it
Masonite 2 adds some improvements with imports. Previously we had to import providers and drivers like:
Because of this, all framework Service Providers will need to cut out the redundant last part. The above code should be changed to:
Masonite 2 brings a more explicit way of declaring Service Providers in your application. You'll need to take your current PROVIDERS
list inside the config/application.py
file and move it into a new config/providers.py
file.
Now all Service Providers should be imported at top of the file and added to the list:
String providers will still work but it is not recommended and will not be supported in current and future releases of Masonite.
There are a few changes in the wsgi.py
file and the bootstrap/start.py
file.
In the wsgi.py
file we should add a new import at the top:
Then change the code logic of bootstrapping service providers from:
to:
and change the logic in bootstrap/start.py
to:
Notice here we split the providers list when the server first boots up into two lists which significantly lowers the overhead of each request.
This change should significantly boost speed performances as providers no longer have to be located via pydoc. You should see an immediate decrease in the time it takes for the application to serve a request. Rough time estimates say that this change should increase the request times by about 5x as fast.
Again, with the addition of the above change, any place you have a duplicated class name like:
You can change it to:
Renamed Request.redirectTo to Request.redirect_to. Be sure to change any of these instances accordingly.
All instances of:
should be changed to:
Also removed the .send()
method completely on the Request
class so all instances of:
Need to be changed to:
Some variable internals have changed to prepend a double underscore to them to better symbolize they are being handled internally. Because of this we need to change any instances of csrf_token to __token in the CSRF Middleware file.
You can check for what the class should look like from the MasoniteFramework/masonite repository
Masonite 2 comes with a new autoloader. This can load all classes in any directory you specify right into the Service Container when the server first starts. This is incredibly useful for loading your models, commands or tasks right into the container.
Simply add a new AUTOLOAD
constant in your config/application.py
file. This is the entire section of the autoload configuration.
By default this points to the app directory where models are stored by default but if you moved your models to other directories like app/models or app/admin/models then add those directories to your list:
Be caution that this will autoload all models into the Service Container with the class name as the key and the class as the binding.
Because of a minor rewrite of the Request class, we now do not need the RedirectionProvider. You can remove the RedirectionProvider completely in your PROVIDERS
list.
There is a new status code provider which adds support for adding custom status codes and rendering better default status code pages such as 400 and 500 error pages. This should be added right above the StartResponseProvider:
The .env got a small upgrade and in order to make the APP_DEBUG
variable consistent, it should be set to either True
or False
. Previously this was set to something like true
or false
.
Masonite 2 also removed the APP_LOG_LEVEL
environment variable completely.
That's it! You're all done upgrading Masonite 1.6 to Masonite 2.0. Build something awesome!
Be sure to read about all the changes in Masonite 2 to ensure that your application is completely up to date with many of the latest decisions and be sure to thoroughly test your application. Feel free to open an issue if any problems arise during upgrading.
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
directory.
All views are rendered with Jinja2 so we can use all the Jinja2 code you are used to. An example view looks like:
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:
This will create a template under resources/templates/hello.html
.
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 Helper Functions documentation for more information.
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:
This will return the view located at resources/templates/dashboard.html
. We can also specify a deeper folder structure like so:
This will look for the view at resources/templates/profiles/dashboard.html
The View
class is loaded into the container so we can retrieve it in our controller methods like so:
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.
If this looks weird to you or you are not sure how the container integrates with Masonite, make sure you read the Service Container documentation
Some views may not reside in the resources/templates
directory and may even reside in third party packages such as a dashboard package. We can locate these views by passing a /
in front of our view.
For example as a use case we might pip install a package:
and then be directed or required to return one of their views:
This will look inside the dashboard.views
package for a dashboard.html
file and return that. You can obviously pass in data as usual.
It's important to note that if you are building a third party package that integrates with Masonite that you place any .html
files inside a Python package instead of directly inside a module. For example, you should place .html files inside a file structure that looks like:
and not inside the package directory. This is a Jinja limitation that says that all templates should be located in packages.
Accessing a global view such as:
will perform a relative import for your Masonite project. For example it will catch:
So if you are making a package for Masonite then keep this in mind in where you should put your templates
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:
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 Service Container documentation.
This will send a variable named id
to the view which can then be rendered like:
This section requires knowledge of Service Providers and how the Service Container works. Be sure to read those documentation articles.
You can also add Jinja2 environments to the container which will be available for use in your views. This is typically done for third party packages such as Masonite Dashboard. You can extend views in a Service Provider in the boot method. Make sure the Service Provider has the wsgi
attribute set to False
. This way the specific Service Provider will not keep adding the environment on every request.
By default the environment will be added using the PackageLoader Jinja2 loader but you can explicitly set which loader you want to use:
The default loader of PackageLoader will work for most cases but if it doesn't work for your use case, you may need to change the loader.
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.
Masonite uses the Cleo package for creating and consuming commands so for more extensive documentation on how to utilize commands themselves, how to get arguments and options, and how to print colorful text to the command line.
Read more about Cleo by visiting the Cleo Documentation.
You can create commands by using craft itself:
This will create a app/commands/HelloCommand.py
file with boilerplate code that looks like this:
Let's create a simple hello name application which prints "hello your-name" to the console.
Where it says command:name
inside the docstring we can put hello
and inside the argument we can put name
like so:
Inside the handle
method we can get the argument passed by specifying self.argument('name')
. Simply put:
That's it! Now we just have to add it to our craft command.
We can add commands to craft by creating a Service Provider and registering our command into the container. Craft will automatically run all the register methods on all containers and retrieve all the commands.
Let's create a Service Provider:
This will create a provider in app/providers/HelloProvider.py
that looks like:
Let's import our command and register it into the container. Also because we are only registering things into the container, we can set wsgi = False
so it is not ran on every request and only before the server starts:
Make sure you instantiate the command. Also the command name needs to end in "Command". So binding HelloCommand
will work but binding Hello
will not. Craft will only pick up commands that end in Command
. This is also case sensitive so make sure Command
is capitalized.
Like normal, we need to add our Service Provider to the PROVIDERS
list inside our config/providers.py
file:
That's it! Now if we run:
We will see our new hello
command:
and if we run:
We will see an output of:
The Request class is initialized when the server first starts and is modified on every request. This means that the Request class acts as a singleton and is not reinitialized on every request. This presents both pros and cons during developing Masonite. It's great to not have to worry about a new object being instantiated everytime but the con is that some attributes need to be reset at the end of the request.
The Request class is loaded into the IOC container first 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 Service Container documentation.
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 but the actual Request object does not change. In other words, the memory address of the Request object is always the same but the class attributes will change of every request. This is done already for you by the Masonite framework itself. 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.
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:
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 Helper Functions documentation.
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:
There is no difference between any HTTP methods (GET, POST, PUT, etc) when it comes to getting input data. They are all retrieved through this .input()
method so there is no need to make a distinction if the request is GET
or POST
We can get all the request input variables such as input data from a form request or GET data from a query string. Note that it does not matter what HTTP method you are using, the input method will know what input data to get dependent on the current HTTP method (GET
, POST
, PUT
, etc)
This will return all the available request input variables for that request as a dictionary.
This method will get all of the request input variables to include any internal framework variables completely handled internally such as __token and __method. You can exclude them by passing in False into the method or specifying it explicitly:
To get a specific input:
This method will get all of the request input variables to include any internal framework variables completely handled internally such as __token and __method. You can exclude them by passing in False into the method or specifying it explicitly:
To get a specific input:
To check if some request input data exists:
You can only get a certain set of parameters if you have a need to do so. This can be used like:
To get the request parameter retrieved from the url. This is used to get variables inside: /dashboard/@firstname
for example.
Sometimes you may want to handle incoming JSON requests. This could be form external API's like Github.
Masonite will detect that an incoming request is a JSON request and put the cast the JSON to a dictionary and load it into the payload request input. For example if you have an incoming request of:
Then we can fetch this input in a controller like so:
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. This is a security measure to ensure malicious Javascript code cannot fetch cookies if they are somehow retrieved. All cookies are set with the HTTP_ONLY flag meaning that Javascript cannot read them although you can turn this off using a parameter.
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:
All cookies are set as session cookies. This means that when the user closes out the browser completely, all cookies will be deleted.
This will set a cookie thats expires 5 minutes from the current time.
Again, as a security measure, all cookies automatically are set with the HttpOnly
flag which makes it unavailable to any Javascript code. You can turn this off:
This will now allow Javascript to read the cookie.
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.:
This will return the plain text version of the cookie.
If Masonite attempts to decrypt a cookie but cannot then Masonite will assume that the secret key that encrypted it was changed or the cookie has been tampered with and will delete the cookie completely.
If your secret key has been compromised then you may change the key at anytime and all cookies set on your server will be removed.
You may also delete a cookie. This will remove it from the browser.
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 also get a route URL via the route name. Let's say we have a route like this:
We can get the URL from the route name like so:
if we have route parameters like this:
then we can pass in a dictionary:
We can get the current url with:
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
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
.
Redirecting to a named route with URL parameters:
Redirecting to a url in your application with URL parameters:
There will be plenty of times you will need to redirect back to where the user came just came from. In order for this work we will need to specify where we need to go back to. We can use the back method for this.
There are 3 states which we should be aware of when using this method.
Masonite will check for a __back
input and redirect to that route. We can specify one using the back()
view helper function:
This will route back to the form when you run this back method
The next state is using the back method without any parameters or form helpers:
This will redirect back to the current route. This might be useful we have have routes like:
Where we are going to the POST
version but want to redirect back to the GET
version of the route.
We can also specify a default route just in case a form submitted does not specify one using a form helper:
This will check for the __back
input and if it doesn't exist it will use this default route.
Where we are going to the POST
version but want to redirect back to the GET
version of the route.
We can also specify a default route just in case a form submitted does not specify one using a form helper:
This will check for the __back
input and if it doesn't exist it will use this default route.
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 for testing and development purposes.
You can also get and set any headers that the request has.
You can get all WSGI information by printing:
This will print the environment setup by the WSGI server. Use this for development purposes.
You can also get a specific header:
This will return whatever the HTTP_AUTHORIZATION
header if one exists. If that does not exist then the AUTHORIZATION
header will be returned. If that does not exist then None
will be returned.
We can also set headers:
Masonite will automatically prepend a HTTP_
to the header being set for standards purposes so this will set the HTTP_AUTHORIZATION
header. If you do not want the HTTP
prefix then pass a third parameter:
This will set the AUTHORIZATION
header instead of the HTTP_AUTHORIZATION
header.
Masonite will set a status code of 404 Not Found
at the beginning of every request. If the status code is not changed throughout the code, either through the developer or third party packages, as it passes through each Service Provider then the status code will continue to be 404 Not Found
when the output is generated. You do not have to explicitly specify this as the framework itself handles status codes. If a route matches and your controller method is about to be hit then Masonite will set 200 OK
and hit your route. This allows Masonite to specify a good status code but also allows you to change it again inside your controller method.
You could change this status code in either any of your controllers or even a third party package via a Service Provider.
For example, the Masonite Entry package sets certain status codes upon certain actions on an API endpoint. These can be 429 Too Many Requests
or 201 Created
. These status codes need to be set before the StartProvider
is ran so if you have a third party package that sets status codes or headers, then they will need to be placed above this Service Provider in a project.
If you are not specifying status codes in a package and simple specifying them in a controller then you can do so freely without any caveats. You can set status codes like so:
This will set the correct status code before the output is sent to the browser. You can look up a list of HTTP status codes from an online resource and specify any you need to. There are no limitations to which ones you can use.
You can get the request method simply:
Typically, forms only have support for GET
and POST
. You may want to change what HTTP method is used when submitting a form such as PATCH
.
This will look like:
or you can optionally use a helper method:
When the form is submitted, it will process as a PUT request instead of a POST request.
This will allow this form to hit a route like this:
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:
Notice how we simply just add builtin functions via this provider.
The Request class has a simple request()
helper function.
is exactly the same as:
Notice we didn't import anything at the top of the file, nor did we inject anything from the Service Container.
The view()
function is just a shortcut to the View
class.
is exactly the same as:
The auth()
function is a shortcut around getting the current user. We can retrieve the user like so:
is exactly the same as:
This will return None
if there is no user so in a real world application this may look something like:
This is because you can't call the .id
attribute on None
We can get the container by using the container()
function
is exactly the same as:
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.
is exactly the same as:
We can resolve anything from the container by using this resolve()
function.
is exactly the same as:
That's it! These are simply just functions that are added to Python's builtin functions.
Die and dump is a common way to debug objects in PHP and other programming languages. Laravel has the concept of dd() which dies and dumps the object you need to inspect.
dd()
is essentially adding a break point in your code which dumps the properties of an object to your browser.
For example we can die and dump the user we find:
If we then go to the browser and visit this URL as normal then we can now see the object fully inspected which will kill the script wherever it is in place and throw an exception but instead of showing the normal debugger it will use a custom exception handler and show the inspection of the object instead:
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.
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
There are what Masonite calls HTTP Middleware which are middleware designed to run on every request and Route Middleware which is middleware designed to only be called on certain requests, such as checking if a user is logged in.
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:
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:
Route middleware have the unique option of also being stacks of middleware (or lists, really). So we can specify a middleware to have a list of middleware instead of one string based middleware:
Notice that we can use both lists and strings for middleware. As a list, all the middleware in the list will run when we call the auth
middleware stack.
There are 4 default middleware that comes with Masonite. These middleware can be changed or removed to fit your application better.
This middleware is design to redirect users to the login page if they are not logged in. This is loaded as a Route Middleware inside config/middleware.py
and design to only be ran on specific routes you specify.
You can run this middleware on any route by specifying the key in the middleware method on your route:
This middleware checks to see if the logged in user has verified their email. If they haven't it will redirect the user to a page reminding them to verify their email.
You can run this middleware on any route by specifying the key in the middleware method on your route:
This middleware is an HTTP Middleware and runs on every request. This middleware checks for the CSRF token on POST
requests. For GET
requests, Masonite generates a new token. The default behavior is good for most applications but you may change this behavior to suit your application better.
This middleware checks if the user is logged in and if so, loads the user into the request object. This enables you to use something like:
Again, middleware should live inside the app/http/middleware
folder and should look something like:
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.
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:
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.
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:
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:
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:
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.
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.
Masonite is bootstrapped via , these providers load features, hooks, drivers and other objects into the which can then be pulled out by you, the developer, and used in your views, middleware and drivers.
With that being said, not all Service Providers need to be ran on every request and there are good times to load objects into the container. For example, loading routes into the container does not need to be ran on every request. Mainly because they won't change before the server is restarted again.
Now the entry point when the server is first ran (with something like craft serve
) is the wsgi.py
file in the root of the directory. In this directory, all Service Providers are registered. This means that objects are loaded into the container first that typically need to be used by any or all Service Providers later. All Service Providers are registered regardless on whether they require the server to be running (more on this later).
Now it's important to note that the server is not yet running we are still in the wsgi.py
file but we have only hit this file, created the container, and registered our Service Providers.
Right after we register all of our Service Providers, we break apart the provider list into two separate lists. The first list is called the WSGIProviders
list which are providers where wsgi=True
(which they are by default). We will use this list of a smaller amount of providers in order to speed up the application since now we won't need to run through all providers and see which ones need to run.
While we are in the loop we also create a list of providers where wsgi=False
and boot those providers. These boot methods may contain things like Manager classes creating drivers which require all drivers to be registered first but doesn't require the WSGI server to be running.
Also, more importantly, the WSGI key is binded into the container at this time. The default behavior is to wrap the WSGI application in a Whitenoise container to assist in the straight forwardness of static files.
This behavior can be changed by swapping that Service Provider with a different one if you do not want to use Whitenoise.
Once all the register methods are ran and all the boot methods of Service Providers where wsgi is false, and we have a WSGI key in the container, we can startup the server by using the value of the WSGI key.
We then make an instance of the WSGI key from the container and set it to an application variable in order to better show what is happening. Then this is where the WSGI server is started.
Now that we have the server running, we have a new entry point for our requests. This entry point is the app function inside bootstrap/start.py.
Now all wsgi servers set a variable called environ. In order for our Service Providers to handle this, we bind it into the container to the Environ key.
Next we run all of our Service Providers where wsgi is true now (because the WSGI server is running).
The Request Life Cycle is now going to hit all of these providers. Although you can obviously add any Service Providers you at any point in the request, Masonite comes with 5 providers that should remain in the order they are in. These providers have been commented as # Framework Providers
. Because the request needs to hit each of these in succession, they should be in order although you may put any amount of any kind of Service Providers in between them.
We enter into a loop with these 5 Service Providers and they are the:
This Service Provider registered objects like the routes, request class, response, status codes etc into the container and then loads the environment into these classes on every request so that they can change with the environment. Remember that we registered these classes when the server first started booting up so they remain the same class object as essentially act as singletons Although they aren't being reinstantiated with the already existing object, they are instantiated once and die when the server is killed.
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:
This provider loads the ability to use sessions, adds a session helper to all views and even attaches a session attribute to the request class.
This provider takes the routes that are loaded in and makes the response object, static codes, runs middleware and other route displaying specific logic. This is the largest Service Provider with the most logic. This provider also searches through the routes, finds which one to hit and executes the controller and controller method.
This provider is responsible for showing the nice HTTP status codes you see during development and production. This Service Provider also allows custom HTTP error pages by putting them into the resources/templates/errors
directory.
Nothing too special about this Service Provider. You can remove this if you want it to show the default WSGI server error.
This Service Provider collects a few classes that have been manipulated by the above Service Providers and constructs a few headers such as the content type, status code, setting cookies and location if redirecting.
Once these 5 providers have been hit (and any you add), we have enough information to show the output. We leave the Service Provider loop and set the response and output which are specific to WSGI. The output is then sent to the browser with any cookies to set, any new headers, the response, status code, and everything else you need to display html (or json) to the browser.
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/providers.py
file, you will find a PROVIDERS
list which contains all the Service Providers involved in building the framework.
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.
We can create a Service Provider but simply using a craft command:
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.
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.
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.
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.
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.
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:
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.
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.
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 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:
Now in our templates we can use:
Which will get the storage/assets/css/style.css
file.
All templates have a static function that can be used to assist in getting locations of static files. You can specify the driver and locations you want using the driver name or dot notation.
Take this for example:
this will render:
You can also make the config location a dictionary and use dot notation:
and use the dot notation like so:
Sometimes you may need to serve files that are normally in the root of your application such as a robots.txt
or manifest.json
. These files can be aliased in your STATICFILES
directory in config/storage.py
. They do not have to be in the root of your project but instead could be in a storage/root
or storage/public
directory and aliased with a simple /
.
For example a basic setup would have this as your directory:
and you can alias this in your STATICFILES
constant:
You will now be able to access localhost:8000/robots.txt
and you will have your robots.txt served correctly and it can be indexed by search engines properly.
Thats it! Static files are extremely simple. You are now a master at static files!
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 its 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:
The craft tool condenses all commonly used commands into its own namespace
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.
When craft is used outside of masonite directory, it will only show a few commands such as the new
and install
commands. Other commands such as commands for creating controllers or models are loaded in from the Masonite project itself.
Many commands are loaded into the framework itself and fetched when craft is ran in a Masonite project directory. This allows version specific Masonite commands to be efficiently handled on each subsequent version as well as third party commands to be loaded in which expands craft itself.
The possible commands for craft include:
You can "tinker" around with Masonite by running:
This command will start a Python shell but also imports the container by default. So we can call:
And play around the container. This is a useful debugging tool to verify that objects are loaded into the container if there are any issues.
Another useful command is the show:routes command which will display a table of available routes that can be hit:
This will display a table that looks like:
If you are trying to debug your application or need help in the Slack channel, it might be beneficial to see some useful information information about your system and environment. In this case we have a simple command:
This will give some small details about the current system which could be useful to someone trying to help you. Running the command will give you something like this:
Feel free to contribute any additional information you think is necessary to the command in the core repository.
To create an authentication system with a login, register and a dashboard system, just run:
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.
Validators are classes based on validating form or request input. We can create validators by running:
Masonite uses Orator which is an active record style ORM. If you are coming from other Python frameworks you may be more familiar with Data Mapper ORM's like Django ORM or SQLAlchemy. These style ORM's are useful since the names of the column in your table are typically the names of class attributes. If you forget what you named your column you can typically just look at the model but if your model looks something like:
Then it is not apparent what the tables are. We can run a simple command though to generate a docstring that we can throw onto our model:
Which will generate something like this in the terminal:
We can now copy and paste that onto your model and change whatever we need to:
If you wish to scaffold a controller, just run:
This command will create a new controller under app/http/controllers/DashboardController.py
. By convention, all controllers should have an appended “Controller” and therefore Masonite will append "Controller" to the controller created.
You can create a controller without appending "Controller" to the end by running:
This will create a app/http/controllers/Dashboard.py file with a Dashboard controller. Notice that "Controller" is not appended.
-e
is short for --exact
. Either flag will work.
You may also create resource controllers which include standard resource actions such as show, create, update, etc:
-r
is short for --resource
. Either flag will work.
You can also obviously combine them:
If you’d like to start a new project, you can run:
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.
Or you can specify the branch you would like to create a new project with:
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 boilerplate of a .env
file. In order to install the dependencies, as well as copy the example environment file to a .env
file, just run:
The craft install
command will also run craft key --store
as well which generates a secret key and places it in the .env
file.
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:
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:
These two flags will create slightly different types of migrations.
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:
You can also refresh and rollback all of your migrations and remigrate them.
This will essentially rebuild your entire database.
You can also rollback all migrations without remigrating
Lastly, you can rollback just the last set of migrations you tried migrating
If you'd like to create a model, you can run:
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:
This will create a model in app/Models/ModelName.py.
Service Providers are a really powerful feature of Masonite. If you'd like to create your own service provider, just run:
This will create a file at app/providers/DashboardProvider.py
Views are simply html files located in resources/templates
and can be created easily from running the command:
This command will create a template at resources/templates/blog.html
You can also create a view deeper inside the resources/templates
directory.
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.
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.
Masonite has a queue feature that allows you to load the jobs you create in the section above and run them either asyncronously or send them off to a message broker like RabbitMQ. You may start the worker by running:
You can scaffold out basic command boilerplate:
This will create a app/commands/HelloCommand.py
file with the HelloCommand
class.
You can run the WSGI server by simply running:
You will likely only use that command in production. For development, you can make the server autoreload after you save a python file, similiar to how Django does.
or the shorthand
You can bind to a host using -b
and/or a port using -p
Masonite comes with a pretty quick auto reloading development server. By default there will be a 1 second delay between file change detection and the server reloading. This is a fairly slow reloading interval and most systems can handle a much faster interval while still properly managing the starting and killing of process PID's.
You can change the interval to something less then 1 using the -i
option:
You will notice a considerably faster reloading time on your machine. If your machine can handle this interval speed (meaning your machine is properly starting and killing the processes) then you can safely proceed using a lower interval during development.
To generate a secret key
, we can run:
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:
This command is ran whenever you run craft install
Great! You are now a master at the craft command line tool.
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.
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 through resolving objects. That's it.
Think of "resolving objects" as Masonite saying "what does your object need? Ok, I have them in this dictionary, let me get them for you."
The container holds all of the frameworks classes and features so adding features to Masonite only entails adding classes into the container to be used by the developer later on. This typically means "registering" these classes into the container (more about this later on).
This allows Masonite to be extremely modular.
There are a few objects that are resolved by the container by default. These include your controller methods (which are the most common and you have probably used them so far) driver and middleware constructors and any other classes that are specified in the documentation.
There are four methods that are important in interacting with the container: bind
, make
and resolve
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:
This will load the key value pair in the providers
dictionary in the container. The dictionary after this call will look like:
The service container is available in the Request
object and can be retrieved by:
In order to retrieve a class from the service container, we can simply use the make
method.
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.
You may want to collect specific kinds of objects from the container based on the key. For example we may want all objects that start with "Exception" and end with "Hook" or want all keys that end with "ExceptionHook" if we are building an exception handler.
We can easily collect all objects based on a key:
This will return a dictionary of all objects that are binded to the container that start with anything and end with "ExceptionHook" such as "SentryExceptionHook" or "AwesomeExceptionHook".
We can also do the opposite and collect everything that starts with a specific key:
This will collect all keys that start with "Sentry" such as "SentryWebhook" or "SentryExceptionHandler."
Lastly, we may want to collect things that start with "Sentry" and end with "Hook"
This will get keys like "SentryExceptionHook" and "SentryHandlerHook"
You can also collect all subclasses of an object. You may use this if you want to collect all instances of a specific class from the container:
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.
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:
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.
You can pass in keys and annotations in any order:
Pretty powerful stuff, eh?
Another powerful feature of the container is it can actually return instances of classes you annotate. For example, all Upload
drivers inherit from the UploadContract
which simply acts as an interface for all Upload
drivers. Many programming paradigms say that developers should code to an interface instead of an implementation so Masonite allows instances of classes to be returned for this specific use case.
Take this example:
Notice that we passed in a contract instead of the upload class. Masonite went into the container and fetched a class with the instance of the contract.
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.
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.
Sometimes we might want to run some code when things happen inside our container. For example we might want to run some arbitrary function about we resolve the Request object from the container or we might want to bind some values to a View class anytime we bind a Response to the container. This is excellent for testing purposes if we want to bind a user object to the request whenever it is resolved.
We have three options: on_bind
, on_make
, on_resolve
. All we need for the first option is the key or object we want to bind the hook to, and the second option will be a function that takes two arguments. The first argument is the object in question and the second argument is the whole container.
The code might look something like this:
Notice that we create a function that accepts two values, the object we are dealing with and the container. Then whenever we run on_make
, the function is ran.
We can also bind to specific objects instead of keys:
This then calls the same attribute but anytime the Request
object itself is made from the container. Notice everything is the same except line 6 where we are using an object instead of a string.
We can do the same thing with the other options:
By default, Masonite will not care if you override objects from the container. In other words you can do this:
Without issue. Notice we are binding twice to the same key. You can change this behavior by specifying 2 values in the constructor of the App
class:
If override is False
, it will not override values in the container. It will simply ignore them if you are trying to bind twice to the same key. If override is True
, which it is by default, you will be allowed to override keys in the container with new values by binding them.
Strict will throw an exception if you try binding a key to the container. So with override being False
it simply ignored binding a key to the container that already exists, setting strict to True
will actually throw an exception.
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.
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:
You can put this file wherever you want but we will put it here for the purposes of this documentation.
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.
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:
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:
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.
In order to check the input data we receive from a request, such as a form submission, we can use this validator like so:
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.
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:
Notice how we passed a dictionary into our .check()
method here and didn't pass the request object in the constructor.
Sometimes you might want to cast a certain value for the purposes of validation. For example you may want to accept a string like California,Florida,Ohio
but want to treat it as a list for the purposes of validation. We might want to make it a list to see if there are between 1 and 3 of them.
To do this simply requires validation casting. When validating, Masonite Validations will look for a cast_x method. x is the name of the input you are validating. So for example we may have an input like this:
When validating, the validator will call this cast_countries method and use the return value as the value to validate. This validation will work because it will split the countries into a list and turn:
into this:
You can also use this validator class to get the value that the validator is using. In other words, if there is a cast method, it will get the casted value. If there is no cast method then it will get the raw value supplied to it.
If a full validation class is a bit too much for you then you can use a smaller helper function. You may choose this option if you are building a simple RESTful API endpoint and just want some quick validation.
This helper function signature looks like:
Messages are optional. If left out it will use the default error messages.
A full implementation looks like:
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 use the method:
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.
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()
.
The Truthy()
validator class will check whatever is truthy to Python. This includes True, non-0 integers, non-empty lists, and strings
This validator will check that a value is equal to the value given.
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.
This validator checks that the dictionary value falls inclusively between the start and end values passed to it.
The Pattern validator checks that the dictionary value matches the regex pattern that was passed to it.
This validator checks that the dictionary value is a member of a collection passed to it.
Usage
Since Orator returns a collection, we can specify an Orator Collection as well:
This validator negates a validator that is passed to it and checks the dictionary value against that negated validator.
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.
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.
This validator checks that the value must have at least minimum elements and optionally at most maximum elements.
Read more about this 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.
Be sure to read the documentation to learn more about validators.
Read more about Service Providers under the documentation.
Jobs will be put inside the app/jobs
directory. See the documentation for more information.
You'll need to read the documentation in the documentation for futher info on how to setup this feature.
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:
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.
Because of Masonite's Service Container, It is extremely easy to make drivers that can be used by simply adding your service provider.
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:
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.
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:
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.
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
:
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:
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
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 Service Providers documentation. For now, we will just register it from within our AppProvider
.
Our AppProvider
class might look something like this:
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:
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:
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!
Status codes are a crucial part of any application. They allow your users to identify exactly what went wrong with your site without showing too much information. By default, Masonite will show generic 404 pages when a url is missed.
When APP_DEBUG is True in your .env file, an exception view is shown to help you debug your application. When it is False then it will show a generic 500 error page.
This behavior is through the StatusCodeProvider
in your PROVIDERS
list. In addition to this behavior we can also show our own error pages.
Masonite will first look for the error that is being thrown in your resources/templates/errors
directory and render that template. If one does not exist then it will return a generic view from the Masonite package itself.
For example if a 404 Not Found error will be thrown then it will first check in resources/templates/errors/404.html
and render that template. This is the same behavior for 500 Server Not Found
errors and other errors thrown.
You'll find yourself needing to add temporary data to an individual user. Sessions allow you to do this by adding a key value pair and attaching it to the user's IP address. You can reset the session data anytime you want; which is usually done on logout or login actions.
The Session features are added to the framework through the SessionProvider
Service Provider. This provider needs to be between the AppProvider
and the RouteProvider
. For Masonite 1.5+, this provider is already available for you.
It's important to note that the Session will default to the memory
driver. This means that all session data is stored in an instantiated object when the server starts and is destroyed when the server stops. This is not good when using a WSGI server like Gunicorn which might use multiple workers because each worker will create it's own memory state and requests may jump from worker to worker unpredictably. If you are only using 1 worker then this won't be an issue as long as the worker doesn't die and reset for the duration of the server's life. In this case you should use another driver that doesn't have the memory issue like the cookie
driver which will store all session information as cookies instead of in memory.
There are a two ideas behind sessions. There is session data and flash data. Session data is any data that is persistent for the duration of the session and flash data is data that is only persisted on the next request. Flash data is useful for showing things like success or warning messages after a redirection.
Session data is automatically encrypted and decrypted using your secret key when using the cookie
driver.
Sessions are loaded into the container with the Session
key. So you may access the Session
class in any part of code that is resolved by the container. These include controllers, drivers, middleware etc:
Data can easily be persisted to the current user by using the set
method. If you are using the memory
driver, it will connect the current user's IP address to the data. If you are using the cookie
then it will simply set a cookie with a s_
prefix to notify that it is a session and allows better handling of session cookies compared to other cookies.
This will update a dictionary that is linked to the current user.
You can also set a dictionary as a session value and it will automatically JSON encode and decode as you set and get the key:
When you get the key from the session it will turn it back into a dictionary.
You can use it on flash as well:
Data can be pulled from the session:
Very often, you will want to see if a value exists in the session:
You can get all data for the current user:
Data can be inserted only for the next request. This is useful when using redirection and displaying a success message.
When using the cookie
driver, the cookie will automatically be deleted after 2 seconds of being set.
You can of course change the drivers on the fly by using the SessionManager
key from the container:
It's important to note that changing the drivers will not change the session()
function inside your templates (more about templates below).
The SessionProvider
attaches a session
attribute to the Request
class. This attribute is the Session
class itself.
The SessionProvider
comes with a helper method that is automatically injected into all templates. You can use the session helper just like you would use the Session
class.
This helper method will only point to the default driver set inside config/session.py
file. It will not point to the correct driver when it is changed using the SessionManager
class. If you need to use other drivers, consider passing in a new function method through your view or changing the driver value inside config/session.py
You could use this to create a simple Jinja include template that can show success, warning or error messages. Your template could be located inside a resources/templates/helpers/messages.html
:
Then inside your working template you could add:
Then inside your controller you could do something like:
or as separate statements
Which will show the correct message and message type.
You can reset both the flash data and the session data through the reset
method.
To reset just the session data:
Or to reset only the flash data:
Remember that Masonite will reset flashed data at the end of a successful 200 OK
request anyway so you will most likely not use the flash_only=True
keyword parameter.
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 which can add configuration files, routes, controllers, views, commands and more.
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. Although you can just as simply build packages for both, as long as you add some sort of Service Provider to your package that can integrate your library into Masonite.
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. Conveniently Masonite comes with several helper functions in order to create all of these.
You can easily create a command like craft mypackage:install
and can scaffold out and install controllers, routes, etc into a Masonite project.
You do not have to use this functionality and instead have the developer copy and paste things that they need to from your documentation but having a great setup process is a great way to promote developer happiness which is what Masonite is all about.
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 PyPi 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:
This will create a file structure like:
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:
Great! Inside the services.py
lets put a configuration setting. This configuration file will be directly added into a Masonite project so you can put doctrings or flagpole comments directly in here:
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.
It's great (and convenient) to add craft commands to a project so developers can use your package more efficiently. You can head over to Creating Commands to learn how to create a command. It only involves a normal command class and a Service Provider.
Head over to that documentation page and create an InstallCommand
and an InstallProvider
. This step should take less than a few minutes. Once those are created we can continue to the adding package helpers below.
Masonite packages allow you to add new migrations to a project. For example, this could be used to add a new package_subscriptions
table if you are building a package that works for subscribing users to Stripe.
Inside the Service Provider you plan to use for your package we can register our directory:
Masonite will find any keys in the container that end with MigrationDirectory
and will add it to the list of migrations being ran whenever craft migrate
and craft migrate:*
commands are ran.
The package_directory
variable contains the absolute path to the current file so the migration directory being added should also be an absolute path to the migration directory as demonstrated here. Notice the ../migrations
syntax. This is going back one directory and into a migration directory there.
Almost done. Now we just need to put our masonite.package
helper functions in our install command. The location we put in our create_or_append_config()
function should be an absolute path location to our package. To help with this, Masonite has put a variable called package_directory
inside the integration.py
file. Our handle method inside our install command should look something like:
Make sure this command is added to your Service Provider and the developer using your package adds it to the PROVIDERS
list as per the Creating Commands documentation.
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.
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:
If you want to be able to make changes without having to constantly reinstall your package then run
This will install your new package into your virtual environment. Go back to your project root so we can run our craft testpackage:install
command. If we run that we should have a new configuration file under config/services.py
.
If you have never set up a package before then you'll need to check how to make a .pypirc
file. This file will hold our PyPi credentials.
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:
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:
Now that your package is on PyPi we can just run:
Then add your Service Provider to the PROVIDERS
list:
and then run:
Remember our Service Provider added the command automatically to craft.
Again, not all packages will need to be installed or even need commands. Only packages that need to scaffold the project or something similar need one. This should be a judgment call on the package author instead of a requirement.
You will know if a package needs to be installed by reading the packages install documentation that is written by the package authors.
These helper functions are used inside the install commands or anywhere else in your package where you need to scaffold a Masonite project.
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:
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:
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:
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:
create_controller(location)
will take a controller from your package and append it under the app.http.controllers
namespace by default.
You can also optionally add a to
parameter to specify which directory you want to install the controller into. The directory will automatically be created.
This will create the controller in app.http.controller.Vendor.Package.ControllerHere.py
Masonite has a Service Container which allows you to add objects into the container and have them auto resolved in controllers and other classes. This is an excellent feature and what makes Masonite so powerful. The most obvious way to load classes into the container is through creating a Service Provider and interacting with the container from there.
With Masonite 2, we can use the builtin autoloader in order to load classes into the container in a much simpler way.
The configuration variable for autoloading is inside the config/application.py
file which contains a list of directories:
Out of the box, Masonite will autoload all classes that are located in the app
directory which unsurprisingly contains all of the application models.
Masonite will go through each directory listed and convert it to a module. For example if given the directory of app/models
it will convert that to app.models
and fetch that module. It will use inspection to go through the entire module and extract all classes imported or defined.
If your code looks something like:
Then the autoloader will fetch three classes: the belongs_to
class, the Model
class and the User
class. The autoloader will then check if the module of the classes fetched are actually apart of the module being autoloaded.
In other words the modules of the above classes are: orator.orm
, config.database
and app
respectively. Remember that we are just autoloaded the app
module so it will only bind the app.User
class to the container with a binding of the class name: User
and the actual object itself: <class app.User.User>
.
All of this autoloading is done when the server is first started but before the WSGI server is ready to start accepting requests so there are no performance hits for this.
Since the app directory is autoloaded, and our User
model is in that directory, the User
model will be loaded into the container when the server starts.
All bindings into the Service Container will be the name of the object as the key and the actual object as the value. So the User
model will be accessed like:
You don't have to keep your models in the app
directory. Feel free to move them anywhere but they will not be autoloaded outside the app directory by default. In order to autoload other directories we can add them to the AUTOLOAD
variable.
For example if we have an app directory structure like:
Then we can edit our AUTOLOAD
variable like so:
And then be able to do:
Being that the container is useful as an IOC container, another use case would be if a third party library needed some models to manipulate and then bind them back into the container. An example of this type of library would be one that needs to change the models methods in order to capture query operations and send them to a dashboard or a report.
The autoload class will raise a few exceptions so you should be aware of them in order to avoid confusion when these exceptions are raised.
This exception will be thrown if any of your autoload paths contain a forward slash like:
Notice the path is now app/ and not app. This will throw an exception when the server first starts.
This exception will be thrown when one of your classes are about to overwrite a container binding that is outside of your search path. The search path being the directories you specified in the AUTOLOAD
constant.
For example, you may have a model called Request
like so:
Without this exception, your application will overwrite the binding of the Masonite Request
class.
When Masonite goes to autoload these classes, it will detect that the Request
key has already been bound into the container (by Masonite itself). Masonite will then detect if that Request
object in the container is within the search path. In other words it will check for a Request
class inside the current module you are autoloading.
If the object is outside of the module you are autoloading then it will throw this exception. In this instance, it will throw an exception because the Request
key in the container is the <class masonite.request.Request> class which is outside of the app
module (and inside the masonite.request
module).
If you find yourself hitting this exception then move the object outside of a directory being autoloaded and into a separate directory outside of the autoloader and then you can manually bind into the container with a different key, or simply rename the class to something else. When using models, you can rename the model to whatever you like and then specify a __table__
attribute to connect the model to the specific table.
Although it is useful to get the model by the actual container key name, it might not be as practical or even the best way to fetch models from the container.
The recommended approach is to simply fetch the class itself by using annotations so you can adjust the variable name and ensure consistency throughout your application.
If this seems like a strange syntax to you, be sure to read the Resolve section of the Service Container documentation.
You may also want to autoload classes yourself. This may be useful if building a package and needing to get all classes from a certain location or even all instances from a certain directory.
This might in useful in the Masonite scheduling feature to grab all the classes that are subclasses of the Task
class.
Autoloading class instances could look something like:
This will fetch all the classes in the app/models
directory that are instances of the Model
class. The classes
attribute contains a dictionary of all the classes it found.
If you don't want to get classes that are instances of another class then we can simply collect classes:
You may have noticed that this autoload class will actually capture all classes found. These classes include the classes that were imported as well.
The default autoload in the config file only loads application specific classes.
We can only get application specific classes by passing a parameter in:
This will check the namespace on the class found and make sure it is apart of the path that is being searched.
The classes that the autoloader finds are just classes themselves which are uninstantiated. This is great for fetching models but won't be good for fetching other objects like commands. Commands need to be instantiated when they go into the container by design so they can be found by Masonite and cleo.
We can tell the autoloader to instantiate the class by passing another parameter. This will simply instantiate the object without passing any parameters in.
If your class needs parameters then you should collect the classes and instantiate each one individually.
You can see that now all the objects found are instantiated.
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.
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:
Masonite also supports a Redis driver. Make sure the Redis server is running and:
Add the required environment keys to your .env
file and you are good to go!
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:
We can easily store items into the cache by doing:
This will create a bootstrap/cache/key.txt
file which contains a simple value
.
Also note that the directory will be automatically created if it does not exist.
We may only want to cache something for a few seconds or a few days so we can do something like:
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.
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:
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.
You can also explicitly check if a cache is still valid by doing:
This will return a boolean if a key is valid. This means it is not expired.
We'll have to sometimes check if a cache even exists so we can do that by running:
Which will return a boolean if the cache exists or not.
We may also want to update a cache. For a real world example, this is used for API's for example when updating the cache for rate limiting. This will not reset the expiration, only update the value.
You can delete a cache by key using:
Masonite comes with email support out of the box. Most projects you make will need to send emails upon actions like account creation or notifications. Because email is used so often with software applications, masonite provides mail support with several drivers.
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.
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.
There are two drivers out of the box that masonite uses and there is a tiny bit of configuration for both.
The SMTP driver takes several configuration files we can all put in our .env
file.
Because this is SMTP, we can utilize all SMTP services such as mailtrap and gmail.
You may need to use an ssl version of SMTP depending on the service you are using. You can specify to use SSL by setting that option in your smtp driver configuration in config/mail.py
:
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 does not use SMTP and instead uses API calls to their service to send emails. Mailgun only requires 2 configuration settings:
If you change to using Mailgun then you will need to change the driver. By default the driver looks like:
This means you can specify the mail driver in the .env file:
or we can specify the driver directly inside config/mail.py
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.
The Terminal driver simply prints out your email message in the terminal. Makes testing and development super easy. To use the terminal driver you'll need to enter a few configuration settings.
The Log driver simply prints out your email message into a log file. To use the log driver you'll need to enter a few configuration settings.
Masonite will retrieve the configuration settings for the log driver from the DRIVERS
configuration setting which Masonite has by default, you do not have to change this.
The Mail
class is loaded into the container via the the MailProvider
Service Provider. We can fetch this Mail
class via our controller methods:
We can send an email like so:
You can also obviously specify a specific user:
All mail drivers are managed by the MailManager
class and bootstrapped with the MailProvider
Service Provider.
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:
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:
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.
We can also specify the subject:
You can specify which address you want the email to appear from:
If you don't want to pass a string as the message, you can pass a view template.
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
You are also able to pass data into our mail templates. This data is passed in as a dictionary that contains a key which is the variable with the corresponding value. We can pass data to the function like so:
You'll likely want to seed your database during development in order to get some dummy data into your database to start working fast.
Masonite uses Orator to generate seed files. This documentation will explain how to create the files itself.
Read more about creating seed classes with the .
We can simply create a new seeder by running:
This will create a new seeder inside the databases/seeds
directory. This will also create a database_seeder.py
file which will be where the root of all seeds should be.
The user_table_seeder
should be where you simply abstract your seeds to.
We can run:
This will run the database_seeder
seed. We can also specify an individual seed
Which will run the user_table_seeder
only.
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.
All uploading configuration settings are inside config/storage.py
. The settings that pertain to file uploading are just the DRIVER
and the DRIVERS
settings.
This setting looks like:
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:
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:
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.
You can also explicitly declare the driver as a class:
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:
And inside our controller we can do:
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:
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:
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 store_prepend()
method:
You can upload files directly by passing in a open()
file:
This will upload a file directly from the file system to wherever it needs to upload to.
You can also specify the location you want to upload to. This will default to location specified in the config file but we can change it on the fly:
You can use dot notation to search your driver locations. Take this configuration for example:
and you can use dot notation:
Before you get started with uploading to Amazon S3, you will need the boto3 library:
Uploading to S3 is exactly the same. Simply add your username, secret key and bucket to the S3 setting:
Make sure that your user has the permission for uploading to your S3 bucket.
Then in our controller:
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.
You can also swap drivers on the fly:
or you can explicitly specify the class:
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.
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.
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.
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:
Like every other configuration, you'll need to specify the options inside the DRIVERS
dictionary:
All templates cached will be inside that folder. You may wish to specify another directory for your templates such as:
In order to cache templates for any given amount of time, you can attach the .cache_for()
method onto your view. This looks like:
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:
There are several cache lengths we can use. Below is all the options for caching:
We can cache for several seconds:
or several minutes:
or several hours:
or several days:
or several months:
or even several years:
Very often you will find yourself adding the same variables to a view again and again. This might look something like
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:
As you can see, we bind the view class itself to ViewClass
and the render method to the View
alias.
We can share variables with all templates by simply specifying them in the .share()
method like so:
The best place to put this is in a new Service Provider. Let's create one now called ViewComposer
.
This will create a new Service Provider under app/providers/ViewComposer.py
and should look like this:
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:
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.
Lastly we need to load this into our PROVIDERS
list inside our config/application.py
file.
And we're done! When you next start your server, the request
variable will be available on all templates.
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:
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:
Lastly, we can compose a dictionary for all templates:
Note that this has exactly the same behavior as ViewClass.share()
Jinja2 allows adding filters to your views. Before we explain how to add filters to all of your templates, let's explain exactly what a view filter is.
Filters can be attached to view variables in order to change and modify them. For example you may have a variable that you want to turn into a slug and have something like:
In Python, this slug filter is simply a function that takes the variable as an argument and would look like a simple function like this:
That's it! It's important to note that the variable it is filtering is always passed as the first argument and all other parameters are passed in after so we could do something like:
and then our function would look like:
We can add filters simply using the filter
method on the ViewClass
class. This will look something like:
That's it! Adding filters is that easy!
View tests are simply custom boolean expressions that can be used in your templates. We may want to run boolean tests on specific objects to assert that they pass a test. For example we may want to test if a user is an owner of a company like this:
In order to do this we need to add a test on the View
class. We can do this in a Service Provider. The Service Provider you choose should preferably have a wsgi=False
attribute so the test isn't added on every single request which could potentially slow down the application.
The code is simple and looks something like this:
That's it! Now we can use the a_company_owner
in our templates just like the first code snippet above!
Notice that we only supplied the function and we did not instantiate anything. The function or object we supply needs to have 1 parameter which is the object or string we are testing.
This will add the extension to the view class.
Remember to place this in a service provider where wsgi=False
as this will prevent the extension being added on every request.
Remember that Masonite uses a Service Container and automatic dependency injection. You can read more about it under the documentation.
Read more about creating Jobs and sending emails asynchronously in the documentation.
Make sure that you add filters in a that has wsgi=False
set. This prevents filters from being added on every single request which is not needed.
Jinja2 has the concept of extensions and you can easily add them to your project in a similar way as previous implementations above which is in a :
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.
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
:
and DRIVERS
should hold the configuration data:
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.
If you are using Pusher you will need the Pusher library:
If you are using Ably you will need the ably driver:
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:
We can change the driver on the fly as well:
All drivers have the same methods so don't worry about different drivers having different methods.
We can send data through our WebSocket by running:
That's it! we have just sent a message to anyone subscribed to the channel_name
channel.
We can also send a dictionary:
We can also send a message to multiple channels by passing a list:
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:
Which will pass the event on to whoever is receiving the WebSocket.
You can also swap drivers on the fly:
or you can explicitly specify the class:
Environments in Masonite are defined in .env
files and contain all your secret environment variables that should not be pushed into source control. You can have multiple environment files that are loaded when the server first starts. We'll walk through how to configure your environment variables in this documentation.
Never load any of your .env files into source control. .env
and .env.*
are in the .gitignore
file by default so you should not worry about accidentally pushing these files into source control.
Masonite comes with a LoadEnvironment
class that is called in the bootstrap/start.py
file. This file in imported into the wsgi.py
file which is where the execution of the environment actually happens because of the import.
You likely won't have to use this class since this class handles most use cases by default but we will go over how the class itself works.
In bootstrap/start.py
you will see a code that looks something like:
This class instantiation does a few things:
The first thing is it loads the .env file located in the base of your application into the Python environment. If you installed Masonite using craft install then Masonite automatically create this .env
file for you based on the .env-example
file. If you have installed Masonite but do not see this .env
file then you can create it manually and copy and paste the contents of .env-example
.
The next thing it will do is look for an APP_ENV
variable inside your .env
file it just loaded and then look for an environment with that value.
For example, this variable:
Will load additionally load the .env.local
environment file.
This may be useful to have more global environment variables that can be shared across your team like Stripe, Mailgun, or application keys and then have more developer specific values like database connections, Mailtrap or different storage drivers for development.
In addition to loading the .env
file and the additional environment file defined in your .env
file, you can load a third environment by specifying it in the constructor:
This will load the .env
file, the .env.local
file and the .env.development
environment file.
If you don't want to load an additional environment and instead want to load only 1 single environment then you can pass in the only
parameter.
This will load only the .env.development
environment file.
Framework hooks are essentially events that are emitted that you are able to "hook" into. If you want to add support for Sentry, which is an exception and error tracking solution, then you want to tie into the Exception Hook. When an exception is encountered it will look for your class in the container and execute it.
Currently there is only the Exception Hook that you can tie into but there will be other hooks in later releases of Masonite such as View Hooks and Mail Hooks.
For the purposes of learning about Framework Hooks, we will walk through how to implement Sentry into a Masonite application by adding it to the Exception Hook.
The Exception Hook is fired when an exception is thrown in an application. Anytime you would normally see the debug view when developing is when this hook will fire. This hook may not be fired if the server does not boot up because of an exception depending on how far into the container the exception is thrown but any normal application exceptions encountered will fire this hook.
The exception hook to tie into is ExceptionHook. This means that the key in the container should end with ExceptionHook and Masonite will call it when the Exception Hook is thrown. We can load things into the container such as:
Notice here that our key ends with ExceptionHook and that we instantiated the object. Let's explore creating this entirly from scratch.
Let's explore how we can simply add Sentry to our application. This should take about 5 minutes.
Let's create a class called SentryHook
and put it into app/hooks/sentry.py
.
This should be the basic structure for a hook. All hooks require a load method. This load method will always be passed the application container so it always requires that parameter. From here we can do whatever we need to by making objects from the container.
But for this example we actually don't need the container so we can ignore it.
Ok great so now let's add sentry to our application. You can sign up with Sentry.io which will show you the basic 3 lines you need to add Sentry to any Python project.
This should be the finished hook:
That's it. The key in the client should be available through the Sentry.io dashboard.
Now let's walk through how we can simply tie this into the container so it will be called when an exception is thrown in our project.
Remeber that all we need to do is call is add it to the container and append the correct string to the key.
We can create a new Service Provider to store our hooks so let's make one.
This will create a new Service Provider inside app/providers/HookProvider.py
that looks like:
Now let's just add our hook to it:
Notice that the key we binded our object to ends with "ExceptionHook." What we put before this part of the string is whatever you want to put. Also note that we also instantiated our SentryHook()
and didn't put SentryHook
And finally add the Service Provider to our PROVIDERS
constant in our config/providers.py
file:
That's it! Now everytime an exception is thrown, this will run our SentryHook class that we binded into the container and the exception should pop up in our Sentry.io dashboard.
You can build handlers to handle specific exceptions that are thrown by your application. For example if a TemplateNotFound exception is thrown then you can build a special exception handler to catch that and return a special view or a special debug screen.
Exception handlers are simple classes that have a handle method which accepts the exception thrown:
The constructor of all exception handlers are resolved by the container so you can hint any dependencies you need. Once the constructor is resolved then the handle method will be called.
Once the handle method is called then Masonite will continue with the rest of the WSGI logic which is just setting the status code, headers and returning a response.
Now that we have our exception handler we will need to register it in the container using a special naming convention. The naming convention is: ExceptionNameOfErrorHandler
. The name of the exception that we want to be catching is called TemplateNotFound so we will need to bind this into the container like so:
Almost all applications can make use of queues. Queues are a great way to make time intensive tasks seem immediate by sending the task into the background or into a message queue. 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.
All configuration settings by default are in the config/queue.py
file. Out of the box, Masonite supports 2 drivers:
async
amqp
The async
driver simply sends jobs into the background using multithreading. The amqp
driver is used for any AMQP compatible message queues like RabbitMQ. If you do create a driver, consider making it available on PyPi so others can also install it.
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.
This will create a new job inside app/jobs/SendWelcomeEmail.py
. Our job will look like:
We can run jobs by using the Queue
alias from the container. Let's run this job from a controller method:
Notice in the show method above that we passed in just the class object. We did not instantiate the class. In this instance, Masonite will resolve the controller constructor. All job constructors are able to be resolved by the container so we can simply pass anything we need as normal:
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 Service Container documentation.
We can also instantiate as the job as well if we need to pass in data from a controller method. This will not resolve the job's constructor at all:
The constructor of our job class now will look like:
Whenever jobs are executed, it simply executes the handle method. Because of this we can send our welcome email:
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:
Most of the time you will want to resolve the constructor but pass in variables into the handle()
method. This can be done by passing in an iterator into the args=
keyword argument:
This will pass to your handle method:
The amqp
driver can be used to communicate with RabbitMQ services.
In order to get started with this driver you will need to install RabbitMQ on your development machine (or production machine depending on where you are running Masonite)
You can find the installation guide for RabbitMQ here.
Once you have RabbitMQ installed you can go ahead and run it. This looking something like this in the terminal if ran successfully:
Great! Now that RabbitMQ is up and running we can look at the Masonite part.
Now we will need to make sure our driver and driver configurations are specified correctly. Below are the default values which should connect to your current RabbitMQ configuration. This will be in your app/queue.py
file
If your rabbit MQ instance requires a vhost
but doesn't have a port, we can add a vhost
and set the port to none. vhost
and port
both have the option of being None
. If you are developing locally then vhost
should likely be left out all together. The setting below will most likely be used for your production settings:
We can now start the worker using the queue:work
command. It might be a good idea to run this command in a new terminal window since it will stay running until we close it.
This will startup the worker and start listening for jobs to come in via your Masonite project.
That's it! send jobs like you normally would and it will process via RabbitMQ:
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.
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:
Awesome! We're good to go. All Sass put inside resources/static
will compile into resources/compiled
.
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:
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.
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.
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.
Often your application will require some kind of recurring task that should happen at a specific time of the week, every minute, or every few months. These tasks can be things like:
Reading XML from a directory and importing it into a remote database
Checking if a customer is still a subscriber in Stripe and updating your local database
Cleaning your database of unneeded data every minute or so
Send an API call to a service in order to fire certain events
Or anything in between. There are lots of use cases for simple tasks to be ran during certain parts of the day or even "offline" hours when your employees are gone.
This is feature is not a full queue scheduler that can be used with services like Redis or RabbitMQ. This feature is for running simple tasks like the tasks listed above. For queue support, read the Queues and Jobs documentation.
First we will need to install the scheduler feature. We can simply pip install it:
and then add the Service Provider to our PROVIDERS
list:
This provider will add several new features to Masonite. The first is that it will add two new commands.
The first command that will be added is the craft schedule:run
command which will run all the schedules tasks (which we will create in a bit).
The second command is a craft task
command which will create a new task under the app/tasks
directory.
Now that we added the Service Provider, we can start creating tasks. Let's create a super basic task that prints "Hi". First let's create the task itself:
This will create a file under app/tasks/SayHi.py
This will be the simple boilerplate for our tasks.
All tasks should inherit the scheduler.task.Task
class. This adds some needed methods to the task itself but also allows a way to fetch all the tasks from the container by collecting them.
Make sure you read about collecting objects from the container by reading the Collecting section of the Service Container documentation.
In order for tasks to be discovered they need to be inside the container. Once inside the container, we collect them, see if they need to run and then decide to execute them or not.
There are two ways to get classes into the container. The first is to bind them into the container manually by creating a Service Provider. You can read the documentation on creating Service Providers if you don't know how to do that.
The other way is to Autoload them. Starting with Masonite 2.0, You can autoload entire directories which will find classes in that directory and load them into the container. This can be done by adding the directory your tasks are located in to the AUTOLOAD config variable inside config/application.py:
This will find all the tasks in the app/tasks directory and load them into the container for you with the key binding being the name of the class.
Now that our task is able to be added to the container automatically, let's start building the class.
Firstly, the constructor of all tasks are resolved by the container. You can fetch anything from the container that doesn't need the WSGI server to be running (which is pretty much everything). So we can fetch things like the Upload, Mail, Broadcast and Request objects. This will look something like:
You can either use the annotations here or the usual resolving by the key name:
The handle method is where the logic of the task should live. This is where you should put the logic of the task that should be running recurrently.
We can do something like fire an API call here:
The awesomeness of recurring tasks is telling the task when it should run. There are a few options we can go over here:
A complete task could look something like:
This task will fire that API call every 3 days at 5pm.
All possible options are False
by default. The options here are:
Attribute
Options
Example
run_every
Either a singular or plural version of the accepted time units: minutes
, hours
, days
, months
run_every = '1 day'
run_at
The time in military time ("17:00" for 5pm)
run_at = '17:00'
run_every_hour
Boolean on whether to run every hour or not: True
, False
run_every_hour = True
run_every_minute
Boolean on whether to run every minute or not: True
, False
run_every_minute = True
twice_daily
A tuple on the hours of the day the task should run. Also in military time. (1, 13)
will run at 1am and 1pm.
twice_daily = (1, 13)
If the time on the task is days
or months
then you can also specify a run_at
attribute which will set the time of day it should should. By default, all tasks will run at midnight if days
is set and midnight on the first of the month when months
is set. We can specify which time of day using the run_at
attribute along side the run_every
attribute. This option will be ignored if run_every
is minutes
or hours
.
This feature is designed to run without having to spin up a seperate server command and therefore has some caveats so be sure to read this section to get a full understanding on how this feature works.
Since the scheduler doesn't actually know when the server starts, it doesn't know from what day to start the count down. In order to get around this, Masonite calculates the current day using a modulus operator to see if the modulus of the tasks time and the current time are 0.
For example, if the task above is to be ran (every 3 days) in May then the task will be ran at midnight on May 3rd, May 6th, May 9th, May 12th etc etc. So it's important to note that if the task is created on May 11th and should be ran every 3 days, then it will run the next day on the 12th and then 3 days after that.
After we add the directory to the AUTOLOAD
list, we can run the schedule:run
command which will find the command and execute it.
Masonite will fetch all tasks from the container by finding all subclasses of scheduler.tasks.Task
, check if they should run and then either execute it or not execute it.
Even though we ran the task, we should not see any output. Let's change the task a bit by printing "Hi" and setting it to run every minute:
Now let's run the command again:
We should now see "Hi!" output to the terminal window.
Setting up Cron Jobs are for UNIX based machines like Mac and Linux only. Windows has a similar schedule called Task Scheduler which is similar but will require different instructions in setting it up.
Although the command above is useful, it is not very practical in a production setup. In production, we should setup a cron job to run that command every minute so Masonite can decide on what jobs need to be ran.
We'll show you an example cron job and then we will walk through how to build it.
When a cron job runs, it will typically run commands with a /bin/sh command instead of the usual /bin/bash. Because of this, craft may not be found on the machine so we need to tell the cron job the PATH that should be loaded in. We can simply find the PATH by going to our project directory and running:
Which will show an output of something like:
If you are using a virtual environment for development purposes then you need to run the env
command inside your virtual environment.
We can then copy the PATH and put it in the cron job.
To enter into cron, just run:
and paste the PATH
we just copied. Once we do that our cron should look like:
Exit out of nano. Now we just need to setup the actual cron job:
Now we just need to setup the cron task itself. This could be as easy as copying it and pasting it into the nano editor again. You may need to change a few things though.
The first * * * * *
part is a must and bascially means "run this every minute by default". The next part is the location of your application which is dependant on where you installed your Masonite application.
The next part is dependant on your setup. If you have a virtual environment then you need to activate it by appending && source venv/bin/activate
to the cron task. If you are not running in a virtual environment then you can leave that part out.
Lastly we need to run the schedule command so we can append && craft schedule:run
Great! Now we have a cron job that will run the craft command every minute. Masonite will decide which classes need to be executed.
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.
Make sure you put all your database your credentials and driver into the .env
file. This file is in the .gitignore
file for you so make sure that this file never gets submitted to source control.
If you are using MySQL you can install:
or:
Postgres databases only have a single option for a package:
If you are using SQLite then the configuration will be slightly different. Currently, the configuration is setup to work with MySQL or Postgres but SQLite will need to be adjust slightly to work.
In your config/database.py file we'll just need to remove host, username and password from the configuration settings completely:
Before you start using the ORM you will receive an exception saying that you need to install one of the required packages for your database driver.
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:
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:
This will create a migration that will create a table, as well as migrate the columns you specify.
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.
We can use Orators Schema Builder in order to build our migration file. First lets run a migration craft command to create a blog table:
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:
Inside our with statement we can start adding columns.
Lets go ahead and add some columns that can be used for a blog table.
Ok let's go ahead and break down what we just created.
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 Orator Schema Columns you can use. We'll mention the foreign key here though.
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:
This will set up our column index to be ready for a foreign key. We can easily specify a foreign key by then typing
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.
Check the Orator documentation for more information on creating a migration file.
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:
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:
When we run craft migrate
it will change the column instead of adding a new one.
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:
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.
If you are running a version of Masonite before 1.4 then check the upgrade guide for Masonite 1.3 to 1.4 for learning how to upgrade.
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.
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:
This will add a hidden field that looks like:
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.
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
:
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.
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.
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:
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.
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:
So we can go ahead and make a store
method.
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.
Now that we have our configuration we need injected into our class, we can go ahead and build out the store()
method.:
Ok great! You can see that our store()
method simply takes the file and write the contents of the fileitem
to the disk.
That's it! Drivers are extremely simple and most drivers you create will be a simple class with a single method or two.
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 .
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).
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. 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.
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.
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.
Again, all values passed into bcrypt need to be in bytes so we can pass in a password using the password helper function:
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.
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.
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.
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.
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:
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.
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:
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.
You may change the column to be authenticated by simply changing the column value of the __auth__
class attribute. This will look something like:
This will look inside the email
column now and check that column and password. The authentication column is email
by default.
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:
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?
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_token
column in the table.
Using this LoadUser
middleware you can retrieve the current user using:
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
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:
You can easily log users into your application using the Auth class which takes the request object as a dependency:
Note that the username you supply needs to be in whatever format the __auth__
attribute is on your model. If the email address is the "username", then the user will need to supply their email address.
If you need more direct control internally, you can login by the models ID:
You are now logged in as the user with the ID of 1.
If you only want to login "once", maybe for just authenticating an action or verifying the user can supply the correct credentials, you can login without saving any cookies to the browser:
You can do the same for the normal login method as well:
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:
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
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:
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:
If you wish to require a user to verify their email address and automatically send them an email, you can extend the User
model.
When a user registers this will automatically send them an email asking them to confirm their email address.
You can use the VerifyEmailMiddleware
class to redirect an unverified user.
You can use this middleware in your routes file like so:
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.
Masonite Events is a simple to use integration for subscribing to events. These events can be placed throughout your application and triggered when various actions occur. For example you may want to do several actions when a user signs up like:
Send an email
Subscribe to MailChimp
Update a section of your database
These actions can all be executed with a single line of code in you controller once you have setup your listeners
First we'll need to install the package using pip:
Once installed we'll need to add the provider to our providers list:
This Service Provider will add a new event:listener
command we can use to create new events. We'll walk through step by step on how to create one below.
Masonite Events allows you to subscribe to arbitrary event actions with various event listeners. In this article we will walk through the steps on setting up listeners for a new user subscribing to our application.
We can create our event listener by executing the following command:
This will create a new event in the app/events directory that looks like this:
This is a very simple class. We have the __init__
method which is resolved by the container and we have a handle
method, also resolved by the container.
This means that we can use syntax like:
The subscribe attribute can be used as a shorthand later which we will see but it should be a list of events we want to subscribe to:
We can listen to events simply by passing the listener into one of your applications Service Provider's boot methods. Preferably this Service Provider should have wsgi=False
so that you are not continuously subscribing the same listener on every request.
You likely have a Service Provider whose wsgi attribute is false but let's create a new one:
Make sure we set the wsgi attribute to False:
Now we can import our listener and add it to our boot method:
This is the recommended approach over the more manual approach found below but both options are available if you find a need for one over the other.
Since we have a subscribe attribute on our listener, we can simply pass the action into the subscribe method. This will subscribe our listener to the SomeAction
and the user.subscribed
action that we specified in the subscribe
attribute of our listener class.
If we don't specify the actions in the subscribe attribute, we can manually subscribe them using the listen method in our Service Provider's boot method:
Ensure that the second parameter in the listen method is a list; even if it has only a single value
Now that we have events that are being listened to, we can start firing events. There are two ways to fire events. We can do both in any part of our application but we will go over how to do so in a controller method.
Masonite Events also comes with a new builtin helper method:
Both of these methods will fire all our listeners that are listening to the user.subscribed
event action.
As noted briefly above, we can subscribe to classes as events:
This will go through the same steps as an event subscribed with a string above.
We can also fire events using an * wildcard action:
This will fire events such as user.subscribed
, user.created
, user.deleted
.
We can also fire events with an asterisk in the front:
This will fire events such as user.created
, dashboard.created
and manager.created
.
We can also fire events with a wildcard in the middle:
This will fire events such as user.manager.created
, user.employee.created
and user.friend.created
.
Sometimes you will want to pass an argument from your controller (or wherever you are calling your code) to your event's handle
method. In this case you can simply pass keyword arguments to your fire
method like so:
and you can fetch these values in your handle
method using the argument
method:
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.
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.
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.
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.
If your driver needs additional methods that can be used that are now inside a contract then your documentation should have that caveat listed in a somewhat obvious manner. This means that by the developer using that new method, they will not be able to switch to other drivers freely without hitting exceptions or having to manually use the methods used by the driver.
Therefore it is advisable to not code additional methods on your drivers and just keep to the methods provided by the base class and contract.
Contracts are currently used to create drivers and are located in the masonite.contracts
namespace. Creating a driver and using a contract looks like:
Now this class will constantly throw exceptions until it overrides all the required methods in the class.
It is useful if you want to "code to an interface and not an implementation." This type of programming paradigm allows your code to be very maintainable because you can simply swap out classes in the container that have the same contract.
For example, Masonite has specific manager contracts depending on the type of driver you are trying to resolve. If we are trying to get the manager for the upload drivers, we can resolve that manager via the corresponding upload manager:
Notice this simply returns the specific upload manager used for uploading. Now the upload manager is not a "concrete" implementation but is very swappable. You can load any instance of the the UploadManagerContract
in the container and Masonite will fetch it for you.
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.
Masonite 2.0.0+
Installing Masonite Billing is simple. We just need a new configuration file, 2 new migrations and extend our User model.
Pip Install
Simply add the Masonite Billing Service Provider to your providers list:
This will add a new install:billing command to craft. Just run:
This will create a new configuration file in config/billing.py
All billing information will be located in the config/billing.py file and has 2 important constants:
The DRIVER is the processor that Masonite billing will use and the DRIVERS constant is the configuration setting for the driver.
Although there is the DRIVER constant, Masonite Billing currently only supports Stripe. Other drivers like Braintree will be supported in later releases which should be backwards compatible.
We'll need to create 2 new migrations: one to add columns to the users table and one migration to create a new subscriptions table. Just create these migration files with craft and copy and paste the migration into those files and migrate them.
Let's first add 2 new columns to our users table.
Now just add this column to the migration file:
Now let's add a new subscriptions table.
Now just migrate the new migrations:
Just add your Stripe public and secret keys to your .env file:
Masonite Billing consists of a model that should be inherited by whatever model you want to add subscription billing information to. In this example here, we will focus on adding the billing integration to our User model.
Once that is added we will now have a plethora of methods we can use to subscribe and charge our user.
Read more about how to handle subscription and payment information in the Usage documentation.
Below you will notice we are using a tok_amex token, you may use this token for testing purposes but this token in production should be the token returned when processing your stripe form.
It's also important to note that the subscription records in your database are never deleted but are updated instead. So canceling a subscription does not delete that subscription from your database but only sets when the subscription ended. This is good if you want to dump the data into an email campaign tool to try and get back any lost customers.
To subscribe a user to plans, we can use the subscribe method like so:
This method retuns a string of the subscription token such as sub_j8sy7dbdns8d7sd..
If you try to subscribe a user to a plan and the plan does not exist in Stripe then Masonite will throw a billing.exceptions.PlanNotFound
exception.
If you want to check if the user is subscribed you have a few options:
You may check if the user is subscribed to any plan:
or you can check if the user is subscribed to a specific plan:
You may also check if a user was subscribed but their plan has expired:
or you can obviously check if the user was subscribed to a specific plan:
If you need to get the name of the plan the user is on you can do so using the plan() method:
This will return the name of the plan in Stripe, not the plan ID. For example, our plan ID might be masonite-test but the plan name could be "Awesome Plan."
If the plan you are subscribing a user to has a trial set inside Stripe then the user will be automatically enrolled in a trial for that time. We can check if the user is on a trial using the on_trial() method. In our examples here, the masonite-test plan has a 30 day free trial set inside Stripe.
For example:
We may also want to skip the trial and charge the user immediately for the plan:
We can also specify the amount of days the user should be on a trial for when subscribing them to a plan:
We can swap subscription plans at anytime using the swap() method:
If you want to cancel a user's subscription we can use the cancel() method.
This will cancel the users plan but continue the subscription until the period ends.
Notice here that the last is_subscribed() method still returned True even after we canceled. The user will continue the subscription until the period ends. For example if it is a 1 month subscription and the user canceled 1 week in, Masonite Billing will continue the subscription for the remaining 3 weeks.
If you wish to cancel the user immediately we can specify the now=Trueparameter:
The period between canceling a subscriptions and the period running out can be caught using the user.is_canceled() method:
Again this will only return true if the user has an active subscription but has chosen to cancel it. If the subscription is canceled immediately, this will return False.
If you don't cancel a plan immediately, there will be a period between when the user canceled and when the plan can be resumed. We can use the resume() method here:
Sometimes a user will want to switch or update their card information. We can use the card() method and pass a token to it:
If you want to make one off transactions for customers you can do so easily using the charge() method:
You can charge a card by passing a token:
You can also charge a customer directly by leaving out the token which will charge whatever card the customer has on file.
You can also add a description and metadata (as a dictionary) for the charge:
You will first need to setup coupons in Stripe.
Once you setup a coupon you can use coupons on both charges and subscriptions:
You can also pass in an integer to deduct an amount:
This will deduct 5 dollars frin the 10 dollars you are charging the user.
You can also make a coupon for a certain percentage reduction:
This will deduct 25 percent off.
Webhooks allow your application to interact directly with stripe when certain actions happen such as when a user's subscription has expired. You can use these webhooks to catch any events emitted.
Masonite Billing also allows you to tie into Stripe webhooks. If the subscription is cancelled in Stripe, Stripe will send your server a webhook and Masonite Billing will update the database accordingly.
Be sure to setup the correct url in the the Stripe dashboard inside your Webhook Settings. The url to setup should be http://your-domain.com/stripe/webhook
or if you're testing with Ngrok it should be something like http://684b1285.ngrok.io/stripe/webhook
.
If you go the Ngrok route be sure to read the Testing With Ngrok section
We can simply put the webhook controller in our routes/web.py file just like any other controller but it can point to the packages controller:
This will send all Stripe traffic to the server and handle any hooks accordingly.
Most developers use Ngrok for testing incoming webhooks. Ngrok is a freemium HTTP tunneling service that allows extrernal requests to tunnel into your localhost and port environment. It's exellent for testing things like this as well as other things like OAuth.
If you use Ngrok you will get a subdomain like: http://684b1285.ngrok.io
. Because this is a subdomain, Masonite needs to know which subdomain to support so you're route will have to be:
in order to catch the Ngrok subdomain. This setup will allow you to send test webhooks from Stripe to your server.
You can read more about subdomains in the Subdomain Routing section of the Routing documentation.
External incoming API calls typically will not be able to be CSRF protected because they will not know the specific token connected to a request. We will need to put an exception to the /stripe/webhook route:
Currently the webhook controller only handles when a subscription is canceled but can handle any hook you like. If you need to create a custom hook you can inherit from the WebhookController and add the needed controller methods:
You'll also have to specify a new location of your controller which should now be located in your normal controllers directory:
Events are specific types of webhooks that Stripe will send out when certain actions occur.
You can see a list of stripe events here: https://stripe.com/docs/api#event_types
You'll notice that we have a handle_resource_event method. The WebhookController will take all incoming webhook events into the handle method and dispatch them to other methods.
How it does this is simply takes the event lets say the charge.dispute.created Stripe event (see the link above for a list of more events) and parses it into a string that looks like:
You'll notice we just replaced the . with _ and prefixed a handle to it. This looks like a method call. If we simply create a method now:
This method will be called whenever we receive a webhook for that event. If no method is found for the incoming webhook then the server will return a Webhook Not Supported string which you may see while development testing your Stripe webhooks.
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.
This feature uses for this kind of encryption. Because of this, we can generate keys using Fernet.
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.
This section of the documentation will contain various tutorials. These are guides that are designed to take you from beginning to end on building various types of projects with Masonite. We may not explain things in much detail for each section as this part of the documentation is designed to just get you familiar with the inner workings of Masonite.
Since this section of the documentation is designed to just get you up and coding with Masonite, any further explanations that should be presented are inside various "hint blocks." Once you are done with the tutorial or simply want to learn more about a topic it is advised that you go through each hint block and follow the links to dive deeper into the reference documentation which does significantly more explaining.
You will see various hint blocks throughout the tutorials. Below are examples of what the various colors represent.
You'll see hint blocks that are green which you should follow if you want to learn more information about the topic currently being discussed.
You'll also see hint blocks that are blue. These should not be ignored and typically contain background information you need to further understand something.
This tutorial will assume you have already installed Masonite. If you haven't, be sure to read the Installation guide to get a fresh install of Masonite up and running. Once you have one up and running or if you already have it running, go ahead and continue on.
In this tutorial we will walk through how to create a blog. We will touch on all the major systems of Masonite and it should give you the confidence to try the more advanced tutorials or build an application yourself.
Typically your first starting point for your Masonite development flow will be to create a route. All routes are located in routes/web.py
and are extremely simple to understand. They consist of a request method and a route method. Routing is simply stating what incoming URI's should direct to which controllers.
For example, to create a GET
request route it will look like:
We'll talk more about the controller in a little bit.
You can read more about routes in the Routing documentation
We will start off by creating a view and controller to create a blog post.
A controller is a simple class that holds controller methods. These controller methods will be what our routes will call so they will contain all of our application's business logic.
Think of a controller method as a function in the views.py
file if you are coming from the Django framework
Let's create our first route now. We can put all routes inside routes/web.py
and inside the ROUTES
list. You'll see we have a route for the home page. Let's add a route for creating blogs.
You'll notice here we have a BlogController@show
string. This means "use the blog controller's show method to render this route". The only problem here is that we don't yet have a blog controller.
Let's create the BlogController
in the next step: Part 2 - Creating Our First Controller
All controllers are located in the app/http/controllers
directory and Masonite promotes 1 controller per file. This has proven efficient for larger application development because most developers use text editors with advanced search features such as Sublime, VSCode or Atom. Switching between classes in this instance is simple and promotes faster development. It's easy to remember where the controller exactly is because the name of the file is the controller.
You can of course move controllers around wherever you like them but the craft command line tool will default to putting them in separate files. If this seems weird to you it might be worth a try to see if you like this opinionated layout.
Like most parts of Masonite, you can scaffold a controller with a craft command:
This will create a controller in app/http/controllers
directory that looks like:
Simple enough, right? You'll notice we have a show
method. These are called "controller methods" and are similiar to what Django calls a "view."
Notice we now have our show method that we specified in our route earlier.
We can return a view from our controller. A view in Masonite are html files or "templates". They are not Python objects themselves like other Python frameworks. Views are what the users will see.
This is important as this is our first introduction to Python's IOC container. We specify in our parameter list that we need a view class and Masonite will inject it for us:
Notice here we didn't import anything. This is what Masonite call's "Auto resolving dependency injection". If you don't like the semantics of this there are other ways to "resolve" from the container that you will discover in the reference documentation but for now let's stay with this method of resolving.
Be sure to learn more about the Service Container.
You'll notice now that we are returning the blog
view but it does not exist yet.
All views are in the resources/templates
directory. We can create a new file called resources/templates/blog.html
or we can use another craft command:
This will create that template we wanted above for us.
We can put some text in this file like:
and then run the server
and open up localhost:8000/blog
, we will see "This is a blog"
Most applications will require some form of authentication. Masonite comes with a craft command to scaffold out an authentication system for you. This should typically be ran on fresh installations of Masonite since it will create controllers routes and views for you.
For our blog, we will need to setup some form of registration so we can get new users to start posting to our blog. We can create an authentication system by running the craft command:
We should get a success message saying that some new assets were created. You can check your controllers folder and you should see a few new controllers there that should handle registrations.
We will observe what was created for us in a bit.
In order to register these users, we will need a database. Hopefully you already have some kind of local database setup like MySQL or Postgres. You can open up your MySQL client and create a database. You currently cannot create databases directly through Masonite.
Create a database and name it whatever you like. For the purposes of this tutorial, we can name it "blog"
Once that is done we just need to change a few environment variables so Masonite can connect to the database. These environment variable can be found in the .env
file in the root of the project. Open that file up and you should see a few lines that look like:
Go ahead and change those setting to your connection settings. The DB_DRIVER
constant takes 3 values: mysql
, postgres
and sqlite
.
Since sqlite
has a simpler configuration, you will need to edit config/database.py
to remove the host
, user
, and password
keys.
Once you have set the correct credentials, we can go ahead and migrate the database. Out of the box, Masonite has a migration for a users table which will be the foundation of our user. You can edit this user migration before migrating but the default configuration will suit most needs just fine and you can always add or remove columns at a later date.
This will create our users table for us along with a migrations table to keep track of any migrations we add later.
Now that we have the authentication and the migrations all migrated in, let's create our first user. Remember that we ran craft auth
so we have a few new templates and controllers.
Go ahead and run the server:
and head over to localhost:8000/register and fill out the form. You can use whatever name and email you like but for this purpose we will use:
Now that we have our authentication setup and we are comfortable with migrating our migrations, let's create a new migration where we will store our posts.
Our posts table should have a few obvious columns that we will simplify for this tutorial part. Let's walk through how we create migrations with Masonite.
Not surprisingly, we have a craft command to create migrations. You can read more about Database Migrations here but we'll simplify it down to the command and explain a little bit of what's going on:
This command simply creates the basis of a migration that will create the posts table. By convention, table names should be plural (and model names should be singular but more on this later).
This will create a migration in the databases/migrations
folder. Let's open that up and starting on line 6 we should see something that looks like:
Lets add a title, an author, and a body to our posts tables.
This should be fairly straight forward but if you want to learn more, be sure to read the Database Migrations documentation.
Now we can migrate this migration to create the posts table
Now that we have our tables and migrations all done and we have a posts table, let's create a model for it.
Models in Masonite are a bit different than other Python frameworks. Masonite uses Orator which is an Active Record implementation of an ORM. This bascially means we will not be building our model and then translating that into a migration. Models and migrations are separate in Masonite. Our models will take shape of our tables regardless of what the table looks like.
Again, we can use a craft command to create our model:
Notice we used the singular form for our model. By default, Orator will check for the plural name of the class in our database (in this case posts) by simply appending an "s" onto the model. We will talk about how to specify the table explicitly in a bit.
The model created now resides inside app/Post.py
and when we open it up it should look like:
Simple enough, right? Like previously stated, we don't have to manipulate the model. The model will take shape of the table as we create or change migrations.
Again, the table name that the model is attached to is the plural version of the model (by appending an "s") but if you called your table something different such as "blog" instead of "blogs" we can specify the table name explicitly:
Orator by default protects against mass assignment as a security measure so we will explicitly need to set what columns we would like to be fillable:
The relationship is pretty straight forward here. Remember that we created a foreign key in our migration. We can create that relationship in our model like so:
Because of how Masonite does models, some models may rely on each other so it is typically better to perform the import inside the relationship like we did above to prevent any possibilities of circular imports.
We won't go into much more detail here about different types of relationships but to learn more, read the ORM documentation.
Let's setup a little HTML so we can learn a bit more about how views work. In this part we will setup a really basic template in order to not clog up this part with too much HTML but we will learn the basics enough that you can move forward and create a really awesome blog template (or collect one from the internet).
Now that we have all the models and migrations setup, we have everything in the backend that we need to create a layout and start creating and updating blog posts.
We will also check if the user is logged in before creating a template.
The template for creating will be located at /blog/create
and will be a simple form for creating a blog post
Notice here we have this strange {{ csrf_field|safe }}
looking text. Masonite comes with CSRF protection so we need a token to render with the CSRF field.
Now because we have a foreign key in our posts table, we need to make sure the user is logged in before creating this so let's change up our template a bit:
auth()
is a globally available function that either returns the current user or returns None
.
Masonite uses Jinja2 templating so if you don't understand this templating, be sure to read their documentation.
For simplicity sake, we won't be styling our blog with something like Bootstrap but it is important to learn how static files such as CSS files work with Masonite so let's walk through how to add a CSS file and add it to our blog.
Firstly, head to storage/static/ and make a blog.css file and throw anything you like in it. For this tutorial we will make the html page slightly grey.
Now we can add it to our template like so right at the top:
That's it. Static files are really simple. It's important to know how they work but for this tutorial we will ignore them for now and focus on more of the backend.
Javascript files are the same exact thing:
For more information on static files, checkout the Static Files documentaton.
Notice that our action is going to /blog/create
so we need to direct a route to our controller method. In this case we will direct it to a store
method.
Let's open back up routes/web.py and create a new route. Just add this to the ROUTES
list:
and create a new store method on our controller:
Now notice above in the form we are going to be receiving 2 form inputs: title and body. So let's import the Post
model and create a new post with the input.
Notice that we used Request
here. This is the Request
object. Where did this come from? This is the power and beauty of Masonite and your first introduction to the Service Container. The Service Container is an extremely powerful implementation as allows you to ask Masonite for an object (in this case Request
) and get that object. This is an important concept to grasp so be sure to read the documentation further.
Read more about the Service Container here.
More likely, you will use the request helper and it will look something like this instead:
Notice we used the request()
function. This is what Masonite calls Helper Functions which speed up development. We didn't import anything but we are able to use them. This is because Masonite ships with a Service Provider that adds builtin functions to the project.
Also notice we used an input()
method. Masonite does not discriminate against different request methods so getting input on a GET
or a POST
request doesn't matter. You will always use this input method.
Go ahead and run the server using craft serve and head over to localhost:8000/blog
and create a post. This should hit the /blog/create
route with the POST
request method and we should see "post created".
Lets go ahead and show how we can show the posts we just created. In this part we will create 2 new templates to show all posts and a specific post.
Let's create 2 new templates.
Let's start with showing all posts
Let's create a controller for the posts to separate it out from the BlogController
.
Great! So now in our show
method we will show all posts and then we will create a single
method to show a specific post.
Let's get the show
method to return the posts view with all the posts:
We need to add a route for this method:
Our posts view can be very simple:
Go ahead and run the server and head over to localhost:8000/posts
route. You should see a basic representation of your posts. If you only see 1, go to localhost:8000/blog
to create more so we can show an individual post.
Remember we made our author relationship before. Orator will take that relationship and make an attribute from it so we can display the author's name as well:
Let's repeat the process but change our workflow a bit.
Next we want to just show a single post. We need to add a route for this method:
Notice here we have a @id
string. We can use this to grab that section of the URL in our controller in the next section below.
Let's create a single
method so we show a single post.
We use the param()
method to fetch the id from the URL. Remember this key was set in the route above when we specified the @id
For a real application we might do something like @slug
and then fetch it with request().param('slug')
.
We just need to display 1 post so lets just put together a simple view:
Go ahead and run the server and head over the localhost:8000/post/1
route and then localhost:8000/post/2
and see how the posts are different.
By now, all of the logic we have gone over so far will take you a long way so let's just finish up quickly with updating and deleting a posts. We'll assume you are comfortable with what we have learned so far so we will run through this faster since this is just more of what were in the previous parts.
Let's just make an update method on the PostController
:
Since we are more comfortable with controllers we can go ahead and make two at once. We made one that shows a view that shows a form to update a post and then one that actually updates the post with the database.
Remember we made 2 controller methods so let's attach them to a route here:
That should be it! We can now update our posts.
Let's expand a bit and made a delete method.
Notice we used a GET
route here, It would be much better to use a POST
method but for simplicity sake will assume you can create one by now. We will just add a link to our update method which will delete the post.
We can throw a delete link right inside our update template:
Great! You now have a blog that you can use to create, view, update and delete posts! Go on to create amazing things!
Masonite can handle most of the application that will be built with it. Python is clearly not the fastest language so if it is brute speed to manage 100,000 simultaneous connections than no application written in Python will suit your needs. Those types of application will typically require some Node.js server and asynchronous tasks on multiple servers but if you are going with a Python framework than it is likely you will not need that much juice.
Out of the box, Masonite is designed to run as a great development environment. There are a few trade off's that need to be made in order to stably run Masonite on all operating systems. Masonite defaults to running as the WSGI server with Waitress. This was chosen because waitress is a WSGI server that runs on both Windows and Mac and is powerful enough to run most application during development.
As your application is entering the deployment phase you should look away from running the server with Waitress and look to more production ready options such as uWSGI and Gunicorn. Gunicorn has been tested to run faster than uWSGI both using their default options but uWSGI may be able to be tweaked in a way that is faster dependent on your application.
Because Masonite is simply a WSGI application, any deployment tutorials you research should simply be how to setup a WSGI application on the platform you are trying to deploy to.
So remember, Waitress is great for development but a better WSGI server like Gunicorn should be used when deploying to production.
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.
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:
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.
This will simply add the function as a bound method to the Request
class
We can also extend a class method which will take the method given and add it as a bound method.
We can even extend a whole class which will get all the classes methods and create bound methods to the Request class.
Masonite Dashboard is a barebones dashboard designed for third party packages to add links and views to your dashboard.
These links and views could be:
A payment package adding a setup page to ease in the packages configuration
A CMS to manage your site's content
An API dashboard to monitor API requests
This package does not supply these features but it is up to the community to use this package in order to simply build out functionality on existing dashboards.
Masonite 2.0.8+
First you just need to install the package using PIP:
Just add the provider to the providers list in config/providers.py
:
Next we will just add the routes to our routes list:
A likely use case for this dashboard package is that is should only be used by your team in local development environments. In that case you could set a flag in the routes/web.py
file to only add the routes when APP_DEBUG
is True:
It is wise to check if the user signing into the dashboard is an admin only. We will set an is_admin
flag on our users table by creating a new migration:
And just quickly add a new column:
Great! We are all setup.
We can now go to localhost:8000/dashboard
and be presented with a login page! If you try logging into the dashboard with a user account that is correct but does not have the is_admin flag set then you will see an error like this:
Once logged in correctly with the correct admin privileges, you will be presented with the dashboard screen:
Again, this package is a very basic package and only contains the minimum necessary for third party libraries to create their own admin modules.
The beautiful thing about this dashboard package is that we can now simply add new links and views. There are two classes we need to know about. The dashboard can be expanded by interacting with the Service Container by using Service Providers.
The BaseLink class is a class used for creating navigation links found on the side of the dashboard. Let's walk though how to add a "Hello World" view to the dashboard using this BaseLink.
Let's first create the Service Provider for it:
Great! Now let's create our link. We can do it in the same file as our Service Provider for now but feel free to create a separate file for it.
To create the link we just have to import BaseLink and create a new Link class. You can name your class whatever you want. Masonite Dashboard will find all instances of BaseLink in the container.
The Link
class takes 2 attributes. The display
attribute is what you want the link to display in the navigation menu and the url
is the url that the link will send the user to:
Next we will just bind that class into the container.
Lastly, we just need to put this service provider into the PROVIDERS list:
Now just restart the server (if you aren't running it with the reload option already) and go to the localhost:8000/dashboard
URL again. You should now see a new navigation link:
And if you click on the link it will take you the the URL we decided to use in our Link class:
User links are links that are are found in the user dropdown in the top right when a user is logged in.
The UserLink class works in the exact same way but this time we will inherit from UserLink. Let's look back to our Service Provider and add a new Link.
Again, you can name your class whatever you want. Masonite Dashboard will find all instances of UserLink
from the container.
Now we will see a new link in the user dropdown menu when a user is logged in:
Views are also just as simple. It's is simple as creating a controller like any other view. Let's go through step by step:
Again let's continue with our "hello world" example. Let's make a HelloWorldController:
Now remember, our route was localhost:8000/helloworld so let's add that to our ROUTES list. We'll import a helper for this as well:
Let's add the view to our controller:
Now let's just create the hello.html file. Masonite cannot create directory when adding views so since the resources/templates/dashboard folder does not exist, we need to create it manually.
So go ahead and create that template manually and let's put a small bit of Jinja2 in there:
Notice here we extended from dashboard/base.html. This is the template that contains the sidebar as well as the header for logging in.
Once that is done we can go ahead and open up localhost:8000/dashboard/helloworld and you will see your new hello world template there!
Masonite Notifications can easily add new notification sending semantics for your Masonite project. These notifications could be sending an email or a slack message. This package is designed to be extremely simple and modular so allow new notification abilities to be added to it through third party integrations.
In order to get started using Masonite Notifications, we first have to pip install it:
And then add the provider to our PROVIDERS
list:
Thats it! Let's see how it works!
There are a few concepts we'll need to cover so you can fully understand how Notifications work. First we will cover the high level stuff and then slowly work down into the lower level implementations. For the purposes of this documentation, we will walk through how to setup a welcome notification so we can send an email when a user signs up.
In order to use it we can create a notification class. We can do this simply with a new craft command.
This will create a notification in the app/notifications
directory. Feel free to move it wherever you like though.
This will create a class like so:
Let's now walk through how to build a notification so we can send the email to our user.
Since our notification inherits from Notifiable
, we have access to a few methods we will use to build the notification. We'll show a final product of what it looks like since it's pretty straight forward but we'll walk through it after:
Notice here we are calling a few methods such as driver
, panel
, line
, etc. If we send this message it will look like:
Not bad. We can use this logic to easily build up emails into a nice format simply.
Let's walk through the different options to build an email notification and what they do.
Now that we have built our notification above, we can send it in our controller (or anywhere else we like):
Notice here we simply specified the Notify class in the parameter list and we are able to pass in our awesome new WelcomeNotification into the mail method.
NOTE: The method you should use on the notify class should correspond to the method on the notification class. So for example if we want to execute the slack method on the WelcomeNotification then we would call :
The method you call should be the same as the method you want to call on the notification class. The Notify
class actually doesn't contain any methods but will call the same method on the notification class as you called on the Notify
class.
Out of the box, Masonite notifications comes with Slack support as well in case we want to send a message to a specific slack group.
NOTE: In order to use this feature fully, you'll need to generate a token from Slack. This token should have at minimum the channels:read
, chat:write:bot
, chat:write:user
and files:write:user
permission scopes. If your token does not have these scopes then parts of this feature will not work.
Going back to our WelcomeNotification, we can simply specify a new method called slack
.
Notice the new slack method at the bottom. we will use this method to build our slack notification. Again we will show you a full example and then run through all the methods:
Now that we have built our notification above, we can send it in our controller (or anywhere else we like):
Notice here we simply specified the Notify
class in the parameter list and we are able to pass in our awesome new WelcomeNotification into the slack method.
The Notifiable
class is very modular and you are able to build custom integrations if you like pretty simply. In this section we'll walk through how to create what are called Components
.
Components are classes that can be added to a Notification class that extend the behavior of the notification. In fact, the Notifiable class is just a simple abstraction of two different components. Let's look at the signature of the class that we have been inheriting from.
The Component classes are the classes that have our methods we have been using. If you'd like to see the source code on those components you can check them out on GitHub to get a lower level understanding on how they work.
Let's walk through a bit on how we created our MailComponent by creating a simplified version of it. First let's create a simple class:
Now let's add a line and a subject method to it:
and let's use these two methods to build a template attribute
Since we returned self we can keep appending onto the notification class like we have been.
The actual MailComponent class is a bit more complex than this but we'll keep this simple for explanatory purposes.
Whenever we insert the notification into the Notify class:
This will call the mail method on the notification class (or whatever other method we called on the Notify class).
Once that is returned then it will call the fire_mail method which you will specify in your component.
If you are created a discord notification then you should have a fire_discord
method on your component and you will call it using Notify.discord(WelcomeNotification)
.
Since we want to call the mail method on it, we will create a fire_mail
method:
Sometimes you will want to pass in data into the fire_mail
method. In order to keep this simple and modular, any keyword arguments you pass into the Notify class will be set on the notification class as a protected member. For example if we have this:
It will set a _to
attribute on the notification class BEFORE we get to the fire method.
So using the example above we will be able to do:
We can use this behavior to pass in information into the fire_mail
method while keeping everything clean.
A practical example is sending the message to a certain user:
Notice here we now have a _to
member on our class we can use because we passed it through from our Notify
class.
Ok so finally we have enough information we need to send the actual email. The fire_method is resolved by the container so we can simply specify what we need to send the email.
Our notification class will look like:
Our Notify class will look like:
and our fire method will look like:
Remember the _to
class attribute that came from the keyword argument in the Notify class.
Method
Description
Example
.line()
Creates a single line of text like text you would see in a paragraph tag
line('this is a line of text')
.action()
This creates a clickable looking button. The kwargs include href
and style
. The styles are bootstraps button styles to include default
, success
, danger
, info
etc.
action('Click Me', href="http://google.com", style="danger")
.view()
This is the normal view object here so you can pass in any templates and dictionary you need.
.view('mail/header', {'key': 'value'})
.panel()
This creates a grey background header panel.
.panel('Some Header')
.heading()
Creates a header
.heading('Welcome!')
.subject()
The subject of the email
.subject('New Account!')
.dry()
Sets all the necessary fields but does not actually send the email. This is great for testing purposes. This takes no parameters
.dry()
.driver()
The driver you want to use to send the email
.driver('mailgun')
Method
Description
Example
.token()
This is your Slack token that has the correct permission scopes.
.token('xoxp-359926262626-35...')
.text()
The text you want to show in the message
.text('Welcome to Masonite!')
.channel()
The channel you want to broadcast to. If the value you supply starts with a # sign then Notifications will make a POST request with your token to the Slack channel list API and get the channel ID. You can specify the channel ID directly if you don't want this behavior
.channel('#general') .channel('CHSUU862')
.as_user()
The username you want to show as the message
.as_user('Masonite Bot')
.icon()
The icon you want to show. This needs to be a Slack emoji
.icon(':fire:')
.as_current_user()
This sets a boolean value to True on whether the message should show as the currently authenticated user.
.as_current_user()
.without_markdown()
This will not parse any markdown in the message. This is a boolean value and requires no parameters.
.without_markdown()
.dont_unfurl()
This sets a boolean to False on whether the message should show any attachments. Usually slack will show an icon of the website when posting a link. This disables that feature for the current message.
.dont_unfurl()
.as_snippet()
Used to post the current message as a snippet instead of as a normal message. This option has 3 keyword arguments. The file_type
, name
, and title
. This uses a different API endpoint so some previous methods may not be used.
.as_snippet(file_type='python', name='snippet', title='Awesome Snippet')
.comment()
Only used when using the .as_snippet() method. This will set a comment on the snippet.
.comment('Great Snippet')
.button()
Used to create action buttons under a message. This requires text
and a url
but can also contain style
, and confirm
.button('Sure!', 'http://google.com', style='primary', confirm='Are you sure?')
.dry()
Sets all the necessary fields but does not actually send the email. This is great for testing purposes. This takes no parameters
.dry()
Masonite comes with several drivers that all work great out of the box and in development. Some drivers are better than others in production and some cannot be used in production because of how servers are setup.
For example, the caching or upload drivers should not store anything on the server itself if you are deploying onto an ephemeral deployment platform like Heroku. In these cases you should use a caching driver like Redis and an upload driver like Amazon S3.
The session driver has two options out of the box: memory
and cookie
. The cookie driver will store session data such as success messages, user data or anything else you store with Session.store().
The memory driver will store all session data in a giant dictionary while the server is running and store all data under the IP address. The data will completely lost when the server stops running. The memory driver is great for development and instances where you need to test features without always deleting cookie data.
You can imagine that if you have the memory
driver set and 10,000 users then thats 10,000 dictionary keys each containing several values of session data.
For production, this setting should be set to cookie
to maximize server performance and server resources.