### Install Project Dependencies
Source: https://docs.masoniteproject.com/
After starting a project, run 'project install' to set up all necessary Masonite dependencies. Ensure you are in the project directory before running this command.
```bash
project install
```
--------------------------------
### Install Masonite Package
Source: https://docs.masoniteproject.com/
Use pip to install the Masonite package. This is the first step in setting up your project.
```bash
pip install masonite
```
--------------------------------
### Install NPM Dependencies
Source: https://docs.masoniteproject.com/development/features/compiling-assets
Run this command to install all necessary project dependencies, including those for asset compilation.
```bash
$ npm install
```
--------------------------------
### Start a New Masonite Project
Source: https://docs.masoniteproject.com/
Use the 'project start' command to create a new Masonite project. You can specify a directory name or create it in the current directory.
```bash
project start .
```
```bash
project start my_project
```
--------------------------------
### Basic Masonite Unit Test Example
Source: https://docs.masoniteproject.com/development/testing/getting-started
A simple unit test class that inherits from Masonite's `TestCase`. It includes a `setUp` method for initialization and a basic assertion test. This demonstrates the fundamental structure for writing tests in Masonite.
```python
from masonite.tests import TestCase
class SomeFeatureTest(TestCase):
def setUp(self):
super().setUp()
def test_something(self):
self.assertTrue(True)
```
--------------------------------
### HTML Template Example
Source: https://docs.masoniteproject.com/development/the-basics/views
This is an example of an HTML template file that can be used with Masonite views. It includes a placeholder for a variable.
```markup
Hello, {{ name }}
```
--------------------------------
### Install Vonage Python Client
Source: https://docs.masoniteproject.com/development/features/notifications
Install the necessary Python client for Vonage to enable SMS functionality.
```bash
$ pip install vonage
```
--------------------------------
### Install Masonite 2.3
Source: https://docs.masoniteproject.com/development/upgrade-guide/masonite-2.2-to-2.3
Install the new Masonite version using pip.
```bash
pip install "masonite>=2.3,<2.4"
```
--------------------------------
### Example Cron Job Configuration
Source: https://docs.masoniteproject.com/development/features/scheduling
An example of a cron job entry that runs the Masonite scheduler every minute. It includes setting the PATH and activating a virtual environment.
```cron
PATH=/Users/Masonite/Programming/project_name/venv/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.7/bin
* * * * * cd /Users/Masonite/Programming/project_name && source venv/bin/activate && python craft schedule:run
```
--------------------------------
### Install a Package with Pip
Source: https://docs.masoniteproject.com/development/features/package-development
Use this command to install a package that has been released on PyPi.
```bash
pip install super-awesome-package
```
--------------------------------
### Rename setup_method to setUp
Source: https://docs.masoniteproject.com/development/upgrade-guide/masonite-2.1-to-2.2
Update the test class setup method from setup_method() to setUp() to align with unittest conventions.
```python
from masonite.testing import UnitTest
from routes.web import ROUTES
class TestSomeUnit(UnitTest):
def setup_method(self):
super().setup_method()
self.routes(ROUTES)
```
```python
from masonite.testing import TestCase
class TestSomeUnit(TestCase):
def setUp(self):
super().setUp()
```
--------------------------------
### Define Basic GET Route
Source: https://docs.masoniteproject.com/development/the-basics/routing
Import the Route class and define a GET route within a ROUTES list. This maps the '/welcome' URL to the 'WelcomeController@show' action.
```python
from masonite.routes import Route
ROUTES = [
Route.get('/welcome', 'WelcomeController@show')
]
```
--------------------------------
### Install Masonite Debugbar
Source: https://docs.masoniteproject.com/development/official-packages/masonite-debugbar
Install the masonite-debugbar package using pip.
```bash
pip install masonite-debugbar
```
--------------------------------
### Install API Configuration
Source: https://docs.masoniteproject.com/development/features/api
Run the `craft api:install` command to create a new API configuration file (`config/api.py`). This command also generates a JWT secret key.
```bash
python craft api:install
```
--------------------------------
### Database Configuration for Testing
Source: https://docs.masoniteproject.com/development/testing/database-tests
Example of a `config/database.py` file showing how to define different database connections, including a specific one for testing.
```python
# config/database.py
DATABASES = {
"default": "mysql",
"mysql": {
"host": "localhost",
"driver": "mysql",
"database": "app",
"user": "root",
"password": "",
"port": 3306
}
"testing": {
"driver": "sqlite",
"database": "test_database.sqlite3",
},
}
```
--------------------------------
### Initialize Masonite Project Environment
Source: https://docs.masoniteproject.com/development/features/package-development
Initializes the Masonite project by installing Masonite, development tools, and the local package.
```bash
make init
```
--------------------------------
### Example Policy for Post Model
Source: https://docs.masoniteproject.com/development/features/authorization
An example policy demonstrating custom authorization logic for the Post model, including checks for creating, viewing, and updating posts.
```python
from masonite.authorization import Policy
class PostPolicy(Policy):
def create(self, user):
return user.email == "idmann509@gmail.com"
def view(self, user, instance):
return True
def update(self, user, instance):
return user.id == instance.user_id
```
--------------------------------
### Serve the Masonite Application
Source: https://docs.masoniteproject.com/development/prologue/create-a-blog
Start the development server using the craft serve command. This command will make your application accessible at http://localhost:8000.
```bash
$ python craft serve
```
--------------------------------
### Controller with Facade
Source: https://docs.masoniteproject.com/development/whats-new/masonite-4.0
This example demonstrates using the Response facade for a cleaner syntax to redirect the user to the homepage. Facades offer a proxy to the Service Container.
```python
from masonite.facades import Response
def show(self):
return Response.redirect('/')
```
--------------------------------
### Creating a Custom Facade
Source: https://docs.masoniteproject.com/development/features/facades
This example shows the basic structure for creating your own facade by extending the base Facade class and defining a container key.
```python
from masonite.facades import Facade
class YourFacade(metaclass=Facade):
key = 'container_key'
```
--------------------------------
### Install Cookiecutter
Source: https://docs.masoniteproject.com/development/features/package-development
Install the cookiecutter package globally or locally to scaffold your Masonite package.
```bash
pip install cookiecutter
```
--------------------------------
### Start Tinker Shell
Source: https://docs.masoniteproject.com/whats-new/masonite-2.0.md
Use the `craft tinker` command to start a Python shell with the Masonite container pre-imported. This is a useful debugging tool.
```bash
$ craft tinker
```
--------------------------------
### Method and Function Docstring Example
Source: https://docs.masoniteproject.com/development/prologue/contributing-guide
Methods and functions require docstrings that briefly describe their purpose and provide an example of usage.
```python
def some_function(self):
"""This is a function that does x action.
Then give an exmaple of when to use it
"""
... code ...
```
--------------------------------
### Install Pusher Python Package
Source: https://docs.masoniteproject.com/development/features/broadcasting
Install the necessary Python package for Pusher integration.
```shell
pip install pusher
```
--------------------------------
### Configure .pypirc for PyPI Publishing
Source: https://docs.masoniteproject.com/development/features/package-development
Example .pypirc file configuration using a PyPI API token for authentication.
```ini
[distutils]
index-servers =
pypi
pypitest
[pypi]
username=__token__
password=pypi-AgEIcHlwaS5vcmcCJGNjYjA4M...
```
--------------------------------
### Enter Tinker Shell with IPython
Source: https://docs.masoniteproject.com/development/features/tinker
Use this command to launch the Tinker shell with IPython support for enhanced features like syntax highlighting and tab completion. Ensure IPython is installed (`pip install IPython`).
```bash
python craft tinker -i
```
--------------------------------
### Install Debian/Ubuntu Packages
Source: https://docs.masoniteproject.com/readme.md
Installs essential development packages for Masonite on Debian and Ubuntu-based systems. Ensure your Python 3 version is correctly specified if needed.
```bash
$ sudo apt install python3-dev python3-pip libssl-dev build-essential python3-venv
```
--------------------------------
### Start New Masonite Project
Source: https://docs.masoniteproject.com/readme.md
Create a new Masonite project in the current directory. You can specify a different directory name if needed.
```bash
project start .
```
--------------------------------
### Module Docstring Example
Source: https://docs.masoniteproject.com/development/prologue/contributing-guide
All module files should begin with a module docstring. Ensure there are no leading or trailing spaces around the descriptive sentence.
```python
"""This is a module to add support for Billing users."""
from masonite.request import Request
...
```
--------------------------------
### Scaffold Authentication System
Source: https://docs.masoniteproject.com/development/prologue/create-a-blog
Run this command to generate controllers, routes, and views for authentication. This is typically done on fresh installations.
```bash
$ python craft auth
```
--------------------------------
### Install slackblocks Python API
Source: https://docs.masoniteproject.com/development/features/notifications
Install the slackblocks library to enable advanced Slack notification formatting using Slack Blocks Kit. This is a prerequisite for building complex message structures.
```bash
$ pip install slackblocks
```
--------------------------------
### Build Welcome Email Listener
Source: https://docs.masoniteproject.com/development/features/events
Example of a listener that sends an email when an event is fired. It imports the Mailable class and uses the mail key from the container.
```python
from app.mailables.WelcomeMailable import WelcomeMailable
class WelcomeEmail:
def handle(self, event):
from wsgi import application
application.make("mail").send(
WelcomeMailable().to('idmann509@gmail.com')
)
```
--------------------------------
### Route Parameter Parsing Example
Source: https://docs.masoniteproject.com/development/whats-new/masonite-2.1
Demonstrates how route parameters like '@user' and '@id' are parsed and accessed using the Request class.
```python
from masonite.request import Request
def show(self, request: Request):
request.param('user')
request.param('id')
```
--------------------------------
### Enabling CSRF Protection in setUp()
Source: https://docs.masoniteproject.com/development/testing/http-tests
Enable CSRF protection for all tests in a class by calling withCsrf() within the setUp() method. This ensures all requests in the test class are CSRF protected.
```python
def setUp(self):
super().setUp()
self.withCsrf()
```
--------------------------------
### Define a Route to a Controller Method
Source: https://docs.masoniteproject.com/development/the-basics/controllers
Maps a GET request to the root URL to the 'show' method of the 'WelcomeController'.
```python
Route.get('/', 'WelcomeController@show')
```
--------------------------------
### Using a Custom Facade
Source: https://docs.masoniteproject.com/development/features/facades
Illustrates how to import and use a custom facade after it has been defined.
```python
from app.facades import YourFacade
YourFacade.method()
```
--------------------------------
### Install Masonite 5
Source: https://docs.masoniteproject.com/development/upgrade-guide/masonite-4.x-to-5.x
Uninstall the current version of Masonite and install Masonite 5.0.0.
```bash
pip uninstall masonite
pip install masonite==5.0.0
```
--------------------------------
### Configure Pusher Broadcasting in Python
Source: https://docs.masoniteproject.com/features/broadcasting.md
Set up your Pusher credentials in the `config/broadcast.py` file to enable server-side broadcasting. Ensure the `pusher` package is installed.
```python
config/broadcast.py
#..
BROADCASTS = {
"default": "pusher",
"pusher": {
"driver": "pusher",
"app_id": "3456678",
"client": "478b45309560f3456211", # key
"secret": "ab4229346et64aa8908",
"cluster": "eu",
"ssl": False,
},
}
```
--------------------------------
### Query Documentation Index
Source: https://docs.masoniteproject.com/llms.txt
Perform an HTTP GET request to the documentation index with 'ask' and optional 'goal' parameters to query specific information.
```http
GET https://docs.masoniteproject.com/testing/commands-tests.md?ask=&goal=
```
--------------------------------
### Configure Pusher Broadcasting
Source: https://docs.masoniteproject.com/development/features/broadcasting
Set up your Pusher credentials in the broadcast configuration file. Ensure you have installed the 'pusher' Python package.
```python
"pusher": {
"driver": "pusher",
"app_id": "3456678"
"client": "478b45309560f3456211" # key
"secret": "ab4229346et64aa8908"
"cluster": "eu",
"ssl": False,
},
```
--------------------------------
### Create a New Service Provider
Source: https://docs.masoniteproject.com/development/architecture/service-providers
Use the craft command to generate a new Service Provider file in the `app/providers` directory.
```bash
python craft provider DashboardProvider
```
--------------------------------
### Render Basic View in Controller
Source: https://docs.masoniteproject.com/development/the-basics/views
Renders a 'welcome' template with a 'name' variable. Ensure the template file exists in the `templates` directory.
```python
from masonite.views import View
class WelcomeController(Controller):
def show(self, view: View):
view.render('welcome', {
"name": "Joe"
})
```
--------------------------------
### Create a Basic Controller with Craft Command
Source: https://docs.masoniteproject.com/development/the-basics/controllers
Use the 'craft controller' command to quickly generate a new controller class file.
```bash
$ python craft controller Welcome
```
--------------------------------
### Migrate Project
Source: https://docs.masoniteproject.com/development/features/queues
After creating the necessary migration files, execute this command to apply them to your database.
```bash
$ python craft migrate
```
--------------------------------
### Install Memcached Driver
Source: https://docs.masoniteproject.com/features/cache.md
Install the 'pymemcache' Python package using pip. This is required for using the Memcached cache driver.
```bash
pip install pymemcache
```
--------------------------------
### Serve Test Project
Source: https://docs.masoniteproject.com/development/features/package-development
Runs the development server for the test project, allowing you to test your package locally.
```bash
python craft serve
```
--------------------------------
### Install Redis Driver
Source: https://docs.masoniteproject.com/features/cache.md
Install the 'redis' Python package using pip. This is required for using the Redis cache driver.
```bash
pip install redis
```
--------------------------------
### Basic Webpack Mix Configuration
Source: https://docs.masoniteproject.com/development/features/compiling-assets
Configure asset compilation paths for JavaScript and CSS files. This example moves `app.js` and `app.css` to the `storage/compiled` directory.
```javascript
mix
.js("resources/js/app.js", "storage/compiled/js")
.postCss("resources/css/app.css", "storage/compiled/css", [
//
]);
```
--------------------------------
### Uninstall and Install Masonite 3 Requirements
Source: https://docs.masoniteproject.com/upgrade-guide/masonite-2.3-to-3.0.md
Update project dependencies by uninstalling Masonite 2.3 and Orator, then installing Masonite 3.0.
```bash
$ pip uninstall masonite
$ pip uninstall orator
$ pip install masonite==3.0
```
--------------------------------
### Publish Package to PyPI
Source: https://docs.masoniteproject.com/development/features/package-development
Builds and uploads the package to PyPI after ensuring setup.py is up-to-date and a publish token is configured.
```bash
make publish
```
--------------------------------
### Get Messages for a Specific Error Key
Source: https://docs.masoniteproject.com/development/features/validation
Retrieve all messages associated with a specific error key from the MessageBag using the `get()` method.
```python
errors.get('email')
"""
['Your email is required']
"""
```
--------------------------------
### Define a GET Route
Source: https://docs.masoniteproject.com/development/prologue/create-a-blog
Define a GET request route in routes/web.py. This route maps incoming URIs to specific controller methods.
```python
from masonite.routes import Route
ROUTES = [
Route.get('/url', 'Controller@method')
]
```
--------------------------------
### Install Debian/Ubuntu Packages
Source: https://docs.masoniteproject.com/
Installs necessary development packages for Python and OpenSSL on Debian/Ubuntu based systems. Ensure you are using Python 3.7+.
```bash
$ sudo apt install python3-dev python3-pip libssl-dev build-essential python3-venv
```
```bash
$ sudo apt-get install python3.7-dev python3-pip libssl-dev build-essential python3-venv
```
--------------------------------
### Get Data from Cache
Source: https://docs.masoniteproject.com/development/features/cache
Retrieve data from the cache using the `get` method. If the data has expired, it returns `None` or a specified default value.
```python
cache.get('age', '40')
```
--------------------------------
### API Configuration File Example
Source: https://docs.masoniteproject.com/features/api.md
Configure API settings, including JWT algorithm, secret, model, and authentication behavior. The `authenticates` key determines if tokens are validated against the database on each request.
```python
"""API Config"""
from app.models.User import User
from masonite.environment import env
DRIVERS = {
"jwt": {
"algorithm": "HS512",
"secret": env("JWT_SECRET"),
"model": User,
"expires": None,
"authenticates": False,
"version": None,
}
}
```
--------------------------------
### Basic Service Provider Structure
Source: https://docs.masoniteproject.com/development/architecture/service-providers
A simple Service Provider demonstrating the `register` and `boot` methods. The `register` method binds a class to the container, and the `boot` method can access and use registered classes.
```python
from masonite.providers import Provider
class YourProvider(Provider):
def __init__(self, application):
self.application = application
def register(self):
self.application.bind('User', User)
def boot(self):
print(self.application.make('User'))
```
--------------------------------
### Uninstall Masonite 3 and Install Masonite 4
Source: https://docs.masoniteproject.com/development/upgrade-guide/masonite-3.0-to-4.0
Uninstall the current version of Masonite 3 and install Masonite 4.0.0. Ensure you are using Python 3.7+.
```bash
$ pip uninstall masonite
$ pip install masonite==4.0.0
```
--------------------------------
### Create .pypirc Configuration File
Source: https://docs.masoniteproject.com/development/features/package-development
Creates a .pypirc file in the home directory for PyPI configuration.
```bash
make pypirc
```
--------------------------------
### Add Masonite Classifier to setup.py
Source: https://docs.masoniteproject.com/development/features/package-development
Adds the 'Framework :: Masonite' classifier to the setup.py file to make the package discoverable on the Masonite packages list.
```python
# setup.py
classifiers=[
#...
"Framework :: Masonite",
]
```
--------------------------------
### Install Masonite in Editable Mode
Source: https://docs.masoniteproject.com/development/prologue/contributing-guide
Install the Masonite package in editable mode within your virtual environment. This allows immediate reflection of code changes in your project.
```bash
pip install -e .
```
--------------------------------
### Start a Default Queue Worker
Source: https://docs.masoniteproject.com/development/features/queues
Run the queue:work command in your terminal to start a process that listens for and processes jobs from the queue using default configurations.
```bash
$ python craft queue:work
```
--------------------------------
### Install Masonite CLI Version 2.0
Source: https://docs.masoniteproject.com/development/whats-new/masonite-1.6
Install the latest version of the Masonite CLI, which has been moved into the Masonite repository. This ensures commands are maintained per Masonite version.
```bash
pip install masonite-cli==2.0 --user
```
--------------------------------
### Conditional Validation Example
Source: https://docs.masoniteproject.com/development/features/validation
Use the 'when' clause to apply rules only if a condition is met. This example requires terms to be accepted only if the user's age is less than 18.
```python
"""
{
'age': 15,
'email': 'user@email.com',
'terms': 'on'
}
"""
validate.when(
validate.less_than('age', 18)
).then(
validate.required('terms'),
validate.accepted('terms')
)
```
--------------------------------
### Crontab with PATH and Virtual Environment Activation
Source: https://docs.masoniteproject.com/development/features/scheduling
An example of a crontab entry after pasting the PATH and including virtual environment activation. This ensures the cron job runs with the correct environment and dependencies.
```cron
PATH=/Users/Masonite/Programming/masonitetesting/venv/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.7/bin
```
--------------------------------
### Scaffold Authentication Files
Source: https://docs.masoniteproject.com/development/features/authentication
Run this command to generate controllers, views, and mailables for a basic authentication system.
```python
python craft auth
```
--------------------------------
### Create Resource Controllers
Source: https://docs.masoniteproject.com/development/whats-new/masonite-1.6
Generate resource controllers with predefined actions like show, store, create, and update using the `-r` flag. This promotes better organization by creating one controller per action type.
```bash
craft controller Dashboard -r
```
--------------------------------
### Install Specific Debian/Ubuntu Python Version Packages
Source: https://docs.masoniteproject.com/readme.md
Installs development packages for a specific Python 3 version on Debian/Ubuntu systems. Adjust 'python3.7' to your target Python version.
```bash
$ sudo apt-get install python3.7-dev python3-pip libssl-dev build-essential python3-venv
```
--------------------------------
### Importing and Using Request Facade
Source: https://docs.masoniteproject.com/development/features/facades
Demonstrates importing the Request facade from the masonite.facades namespace and accessing input data.
```python
from masonite.facades import Request
def show(self):
avatar = Request.input('avatar_url')
```
--------------------------------
### Initialize Pusher Client Instance
Source: https://docs.masoniteproject.com/development/features/broadcasting
Create a Pusher instance on the client-side, configuring it with your application cluster.
```javascript
const pusher = new Pusher("478b45309560f3456211", {
cluster: "eu",
});
```
--------------------------------
### Install Enterprise Linux Packages
Source: https://docs.masoniteproject.com/
Installs development packages for Python and OpenSSL on Enterprise Linux distributions like Fedora, CentOS, and RHEL. Use 'dnf' for newer versions.
```bash
# dnf install python-devel openssl-devel
```
--------------------------------
### Mail Facade Type Hinting Example
Source: https://docs.masoniteproject.com/development/features/facades
This is a partial example of type hinting for the Mail facade, used to provide code intelligence in editors. Note the absence of 'self' and the use of '...' for method bodies.
```python
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..mail import Mailable
class Mail:
"""Handle sending e-mails from Masonite via different drivers."""
def mailable(mailable: "Mailable") -> "Mail":
...
def send(driver: str = None):
...
```
--------------------------------
### Update bootstrap/start.py Logic
Source: https://docs.masoniteproject.com/development/upgrade-guide/masonite-1.6-to-2.0
Modify the `bootstrap/start.py` file to correctly boot the WSGI providers after the split.
```python
for provider in container.make('WSGIProviders'):
container.resolve(located_provider.boot)
```
--------------------------------
### Update Service Provider Boot Methods
Source: https://docs.masoniteproject.com/development/upgrade-guide/masonite-2.0-to-2.1
Ensure that `boot` methods in your Service Providers correctly type hint dependencies like `Request`.
```python
def boot(self, request: Request):
..request..
```
--------------------------------
### Get Cookie Value
Source: https://docs.masoniteproject.com/development/the-basics/views
Retrieve the value of a specific cookie.
```html
Token: {{ cookie('token') }}
```
--------------------------------
### Get Session Value
Source: https://docs.masoniteproject.com/development/the-basics/views
Access values stored in the session, such as error messages.
```html
Error: {{ session().get('error') }}
```
--------------------------------
### Show All Posts Method
Source: https://docs.masoniteproject.com/development/prologue/create-a-blog
Retrieves all posts from the database and passes them to the 'posts' view for rendering. Ensure the Post model is imported.
```python
from app.models.Post import Post
...
def show(self, view: View):
posts = Post.all()
return view.render('posts', {'posts': posts})
```
--------------------------------
### Get Request Path
Source: https://docs.masoniteproject.com/development/the-basics/views
Access the current request path within your views.
```html
Path: {{ request().path }}
```
--------------------------------
### Publish Package Resources
Source: https://docs.masoniteproject.com/development/features/package-development
Command to publish all registered package resources into a user's project. Specify the package name declared in `configure()`.
```bash
$ python craft package:publish super_awesome
```
--------------------------------
### Update Post Routes
Source: https://docs.masoniteproject.com/development/prologue/create-a-blog
Define GET and POST routes for the post update functionality.
```python
Route.get('/post/@id/update', 'PostController@update'),
Route.post('/post/@id/update', 'PostController@store')
```
--------------------------------
### Test Class Life Cycle with setUpClass and tearDownClass
Source: https://docs.masoniteproject.com/development/testing/getting-started
Define class-level setup and teardown methods that are executed once before and after all tests in a class, respectively. Useful for expensive resource initialization.
```python
class TestFeatures(TestCase):
@classmethod
def setUpClass(cls):
"""Called once before all tests of this class are executed."""
print("Setting up test class")
@classmethod
def tearDownClass(cls):
"""Called once after all tests of this class are executed."""
print("Cleaning up test class")
def setUp(self):
"""Called once before each test are executed."""
super().setUp()
print("Setting up individual unit test")
def tearDown(self):
"""Called once after each test are executed."""
super().tearDown()
print("Cleaning up individual unit test")
def test_1(self):
print("Running test 1")
def test_2(self):
print("Running test 2")
```
--------------------------------
### Route for All Posts
Source: https://docs.masoniteproject.com/development/prologue/create-a-blog
Defines a GET route for '/posts' that maps to the 'show' method in the PostController.
```python
Route.get('/posts', 'PostController@show')
```
--------------------------------
### Create a New Test File with Craft
Source: https://docs.masoniteproject.com/development/testing/getting-started
Use the Craft command-line tool to generate a new test file and a basic test class structure. This command creates a file in the `tests/unit/` directory.
```bash
python craft test SomeFeatureTest
```
--------------------------------
### Get Host
Source: https://docs.masoniteproject.com/development/the-basics/request
Retrieves the host from the current request. Assumes the host is in the format subdomain.example.com.
```python
from masonite.request import Request
#..
def show(self, request: Request):
# URI: work.example.com
request.get_host() #== example.com
```
--------------------------------
### Get Subdomain
Source: https://docs.masoniteproject.com/development/the-basics/request
Retrieves the subdomain from the current host. Assumes the host is in the format subdomain.example.com.
```python
from masonite.request import Request
#..
def show(self, request: Request):
# URI: work.example.com
request.get_subdomain() #== work
```
--------------------------------
### Get Current Environment
Source: https://docs.masoniteproject.com/development/the-basics/environments
Access the current application environment using the app.environment() helper.
```python
app.environment() #== local
```
--------------------------------
### List All Routes
Source: https://docs.masoniteproject.com/development/the-basics/routing
Use the 'craft routes:list' command to display all application routes in a table format.
```bash
python craft routes:list
```
--------------------------------
### Get Request Method
Source: https://docs.masoniteproject.com/development/the-basics/request
Retrieves the current request method. Ensure the Request class is imported.
```python
from masonite.request import Request
#..
def show(self, request: Request):
request.get_request_method() #== PUT
```
--------------------------------
### Registering a Service Provider
Source: https://docs.masoniteproject.com/development/architecture/service-providers
Add your custom Service Provider to the `PROVIDERS` list in the `config/providers.py` file to enable its functionality within the framework.
```python
PROVIDERS=[
#..
UserModelProvider,
]
```
--------------------------------
### Publish Package Resources
Source: https://docs.masoniteproject.com/development/features/package-development
Execute this command to publish package resources, such as configuration files or assets, if you need to customize them within your project.
```bash
python craft package:publish super-awesome-package
```
--------------------------------
### Get Request Path
Source: https://docs.masoniteproject.com/development/the-basics/request
Retrieves the current request URI. Ensure the Request class is imported.
```python
from masonite.request import Request
#..
def show(self, request: Request):
request.get_path() #== /dashboard/1
```
--------------------------------
### Upgrade Masonite CLI
Source: https://docs.masoniteproject.com/development/upgrade-guide/masonite-2.0-to-2.1
Ensure you have the latest version of the Masonite CLI installed for compatibility with Masonite 2.1.
```bash
$ pip install masonite-cli --upgrade
```
--------------------------------
### Wrap Application in Exception Handling
Source: https://docs.masoniteproject.com/development/upgrade-guide/masonite-1.5-to-1.6
Update the `bootstrap/start.py` file to wrap the application bootstrapping process in a try-except block. This enables improved exception handling, including the new debug view and future integrations like Sentry.
```python
try:
for provider in container.make('Application').PROVIDERS:
located_provider = locate(provider)().load_app(container)
if located_provider.wsgi is True:
container.resolve(located_provider.boot)
except Exception as e:
container.make('ExceptionHandler').load_exception(e)
```
--------------------------------
### Update Masonite Requirements
Source: https://docs.masoniteproject.com/development/upgrade-guide/masonite-2.3-to-3.0
Uninstall Masonite 2.3 and Orator, then install Masonite 3.0 using pip.
```bash
pip uninstall masonite
pip uninstall orator
pip install masonite==3.0
```
--------------------------------
### Example Environment Variable Output
Source: https://docs.masoniteproject.com/development/features/scheduling
Sample output from the 'env' command, showing the PATH variable. This output is used to configure the cron job's environment.
```text
...
__CF_USER_TEXT_ENCODING=0x1F5:0x0:0x0
PATH=/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.7/bin
PWD=/Users/Masonite/Programming/masonite
...
```
--------------------------------
### Add New Providers to Configuration
Source: https://docs.masoniteproject.com/development/upgrade-guide/masonite-4.x-to-5.x
Include `PresetsProvider`, `SecurityProvider`, and `LoggingProvider` in the `PROVIDERS` list in `config/providers.py`.
```python
from masonite.providers import PresetsProvider, SecurityProvider, LoggingProvider
#...
PROVIDERS = [
FrameworkProvider,
HelpersProvider,
SecurityProvider, # insert here
LoggingProvider, # insert here
RouteProvider,
#..
ValidationProvider,
PresetsProvider, # insert here
AuthorizationProvider,
ORMProvider,
AppProvider,
]
```
--------------------------------
### Define APP_ENV in .env
Source: https://docs.masoniteproject.com/development/the-basics/environments
This is the base .env file that defines the application environment. It is copied to .env during installation.
```bash
APP_ENV=local
```
--------------------------------
### Get All Errors from MessageBag
Source: https://docs.masoniteproject.com/development/features/validation
Retrieve all validation errors stored in the MessageBag as a dictionary. Useful for displaying all errors at once.
```python
errors.all()
"""
{
'email': ['Your email is required'],
'name': ['Your name is required']
}
"""
```
--------------------------------
### Delete Post Route
Source: https://docs.masoniteproject.com/development/prologue/create-a-blog
Define a GET route for deleting a post. A POST route is recommended for production.
```python
Route.get('/post/@id/delete', 'PostController@delete')
```
--------------------------------
### Get Configuration Value
Source: https://docs.masoniteproject.com/development/the-basics/views
Fetch configuration values directly within your templates, like the application name.
```html
App Name: {{ config('application.name') }}
```
--------------------------------
### Ask a Question via Documentation API
Source: https://docs.masoniteproject.com/development
Use this GET request to query the documentation index for specific information. Provide a clear 'ask' parameter for your question and an optional 'goal' parameter to refine the results.
```http
GET https://docs.masoniteproject.com/features/package-development.md?ask=&goal=
```
--------------------------------
### Create Posts Table Migration
Source: https://docs.masoniteproject.com/development/prologue/create-a-blog
Use this command to generate a new migration file for creating the 'posts' table. Ensure table names are plural.
```bash
$ python craft migration create_posts_table --create posts
```
--------------------------------
### Get Current Authenticated User Email
Source: https://docs.masoniteproject.com/development/the-basics/views
Access the email of the currently authenticated user. Equivalent to request.user().
```html
User: {{ auth().email }}
```
--------------------------------
### Basic HTTP Request Test
Source: https://docs.masoniteproject.com/development/testing/http-tests
Make a GET request to the root path and assert that the response is OK.
```python
def test_basic_request(self):
self.get("/").assertOk()
```
--------------------------------
### Create API Controller Resource
Source: https://docs.masoniteproject.com/features/api.md
Use the craft command to generate a controller with standard API methods (index, show, store, update, destroy).
```bash
$ python craft controller api/UsersController -a
```