26
loading...
This website collects cookies to deliver better user experience
create and activate a virtual environment using your preferred method for doing so.
install masonite pip install masonite
confirm it installed correct and run command craft help
which should list all of masonite's craft cli commands.
create a new project craft new my_project
cd into the my_project folder and run craft_install
databases/migrations
from masoniteorm.migrations import Migration
class CreateUsersTable(Migration):
def up(self):
"""Run the migrations."""
with self.schema.create("users") as table:
table.increments("id")
table.string("name")
table.string("email").unique()
table.string("password")
table.string("remember_token").nullable()
table.timestamp("verified_at").nullable()
table.timestamps()
def down(self):
"""Revert the migrations."""
self.schema.drop("users")
class CreateUsersTable(Migration):
def up(self):
"""Run the migrations."""
with self.schema.create("users") as table:
table.increments("id")
table.string("username")
table.string("email").unique()
table.string("password")
table.string("remember_token").nullable()
table.timestamp("verified_at").nullable()
table.timestamps()
def down(self):
"""Revert the migrations."""
self.schema.drop("users")
app/User.py
"""User Model."""
from masoniteorm.models import Model
class User(Model):
"""User Model."""
__fillable__ = ["name", "email", "password"]
__auth__ = "email"
"""User Model."""
from masoniteorm.models import Model
class User(Model):
"""User Model."""
__fillable__ = ["username", "email", "password"]
__auth__ = "username"
.env
file, if you don't have a ready to go mysql or postgres database we can use sqlite by just commenting out the database settings from the .env
file.#DB_CONNECTION=mysql
#DB_HOST=127.0.0.1
#DB_PORT=3306
#DB_DATABASE=masonite
#DB_USERNAME=root
#DB_PASSWORD=root
#DB_LOG=True
craft migrate
to run your migrations and create the users table.config/auth.py
AUTH = {
"defaults": {"guard": env("AUTH_GUARD", "web")},
"guards": {
"web": {
"driver": "cookie",
"model": User,
"drivers": { # 'cookie', 'jwt'
"jwt": {"reauthentication": True, "lifetime": "5 minutes"}
},
},
},
}
craft controller Auth
app/http/middleware/CsrfMiddleware.py
exempt = [
"*"
]
app/http/controllers/AuthController.py
add the following."""A AuthController Module."""
from masonite.request import Request
from masonite.view import View
from masonite.controllers import Controller
from masonite.auth import Auth
class AuthController(Controller):
def __init__(self, request: Request, auth: Auth):
## Add Request and Auth as instance properties each route can use
self.request = request
self.auth = auth
def login(self):
username = self.request.input("username")
password = self.request.input("password")
result = self.auth.login(username, password)
return result
def signup(self):
username = self.request.input("username")
email = self.request.input("email")
password = self.request.input("password")
result = self.auth.register({"username": username, "email": email, "password": password})
return result
def logout(self):
self.auth.logout()
return "Logged Out"
routes/web.py
and add the following:"""Web Routes."""
from masonite.routes import Get, Post, Put, Delete, RouteGroup
ROUTES = [
Get("/", "WelcomeController@show").name("welcome"),
RouteGroup([
Post("/login", "AuthController@login").name("login"),
Post("/signup", "AuthController@signup").name("signup"),
Post("/logout", "AuthController@logout").name("logout"),
], prefix="/auth")
]
/auth/signup
with username/email/password it should return a newly created user./auth/login
it will create the cookie and login in the user, returning the data on the logged in user.create your migrations
craft migration Owner --create owners
craft migration Dog --create dogs
both tables will have a one to many relationship to users (users can have many owners and dogs, but each owner and dog below to one user)
the dog table will denote the one to many relationship to owners
let's give owners an name field in their migration
"""Owner Migration."""
from masoniteorm.migrations import Migration
class Owner(Migration):
def up(self):
"""
Run the migrations.
"""
with self.schema.create("owners") as table:
table.increments("id")
table.string("name")
## Field to track which user created the item
table.integer("user_id")
## Defining the field as a foreign key
table.foreign("user_id").references("id").on("users")
table.timestamps()
def down(self):
"""
Revert the migrations.
"""
self.schema.drop("owners")
"""Dog Migration."""
from masoniteorm.migrations import Migration
class Dog(Migration):
def up(self):
"""
Run the migrations.
"""
with self.schema.create("dogs") as table:
table.increments("id")
table.string("name")
## Field to track which user created the item
table.integer("user_id")
## Defining the field as a foreign key
table.foreign("user_id").references("id").on("users")
## Create the field that will be the foreign key
table.integer("owner_id")
## Foreign Key Field tracking id of related owner
table.foreign("owner_id").references("id").on("owners")
table.timestamps()
def down(self):
"""
Revert the migrations.
"""
self.schema.drop("dogs")
craft migrate
create your models craft model Owner
craft model Dog
edit the app/User.py
model to relate users to dogs and owners
"""User Model."""
from masoniteorm.models import Model
from masoniteorm.relationships import has_many
class User(Model):
"""User Model."""
__fillable__ = ["username", "email", "password"]
__auth__ = "username"
## Establish that users can have many dogs
@has_many("id", "user_id")
def dogs(self):
from app.Dog import Dog
return Dog
## Establish that users can have many owners
@has_many("id", "user_id")
def owners(self):
from app.Owner import Owner
return Owner
user.owners
and its associated dogs user.dogs
."""Owner Model."""
from masoniteorm.models import Model
from masoniteorm.relationships import has_many
class Owner(Model):
@has_many("id", "owner_id")
def dogs(self):
from app.Dog import Dog
return Dog
craft controller DogOwner
"""A DogOwnerController Module."""
from masonite.request import Request
from masonite.view import View
from masonite.controllers import Controller
from app.Dog import Dog
from app.Owner import Owner
class DogOwnerController(Controller):
"""DogOwnerController Controller Class."""
def __init__(self, request: Request):
"""DogOwnerController Initializer
Arguments:
request {masonite.request.Request} -- The Masonite Request class.
"""
self.request = request
def get_user_owners(self):
return self.request.user().owners
def get_user_dogs(self):
return self.request.user().dogs
def create_owner(self):
user = self.request.user()
name = self.request.input("name")
print(user)
owner = Owner.create(name=name, user_id=user["id"])
return owner
def create_dog(self):
user = self.request.user()
name = self.request.input("name")
owner_id = self.request.input("owner_id")
dog = Dog.create(name=name, owner_id=owner_id, user_id=user.id)
return dog
"""Web Routes."""
from masonite.routes import Get, Post, Put, Delete, RouteGroup
ROUTES = [
Get("/", "WelcomeController@show").name("welcome"),
RouteGroup([
Post("/login", "AuthController@login").name("login"),
Post("/signup", "AuthController@signup").name("signup"),
Post("/logout", "AuthController@logout").name("logout"),
], prefix="/auth"),
RouteGroup([
Get("/dog", "DogOwnerController@get_user_dogs").name("get_dogs"),
Get("/owners", "DogOwnerController@get_user_owners").name("get_owners"),
Post("/owner", "DogOwnerController@create_owner").name("create_owner"),
Post("/dog", "DogOwnerController@create_dog").name("create_dog"),
], prefix="/dogowner",middleware=["auth"])
]
/dogowner/owner
with a name and it will create a new owner associated with the loggedIn users id and then if you pass a name and owner_id in a post request to /dogowner/dog
it will create a new dog associated with the loggedIn users id and the specified owners id./dogowner/owners
it should return a list of owners created by that user and a get request to /dogowner/dog
should return a list of dogs created by that user. (You can similarly gets all the dogs of an owners with owner.dogs
)