Skip to content

Commit

Permalink
Next Minor (2.0.25 - 10/7) (#416)
Browse files Browse the repository at this point in the history
* Minor release 2.0.25

* Added MailLogDriver

* Fixed docstring

* Finished up both drivers

* Added tests for new mail drivers

* Remove mail.log and add tear down method

* Added test for terminal driver

* added amqp queue driver support

* fixed amqp driver

* queue classes are resolved via the container and objects are not

* updated docstrings

* cleaned up queue work command

* cleaned up files

* added module docstring

* added location to mail log driver

* fixed mail driver

* fixed mail driver

* added model docstring command

* fixed command imports

* bumped version
  • Loading branch information
josephmancuso committed Oct 7, 2018
1 parent 489e129 commit f7a08c2
Show file tree
Hide file tree
Showing 13 changed files with 332 additions and 6 deletions.
24 changes: 24 additions & 0 deletions masonite/commands/ModelDocstringCommand.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
""" A ModelDocstringCommand Command """

from cleo import Command

from config.database import DB


class ModelDocstringCommand(Command):
"""
Generate a model docstring based on a table definition
model:docstring
{table : Name of the table to generate the docstring for}
"""

def handle(self):
conn = DB.get_schema_manager().list_table_columns(self.argument('table'))
docstring = '"""Model Definition (generated with love by Masonite) \n\n'
for name, column in conn.items():
length = '({})'.format(column._length) if column._length else ''
docstring += '{}: {}{} default: {}\n'.format(
name, column.get_type(), length, column.get_default())

print(docstring + '"""')
51 changes: 51 additions & 0 deletions masonite/commands/QueueWorkCommand.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
""" A QueueWorkCommand Command """

import inspect
import pickle

from cleo import Command

from config import queue
from masonite.exceptions import DriverLibraryNotFound


def callback(ch, method, properties, body):
from wsgi import container
job = pickle.loads(body)
if inspect.isclass(job):
job = container.resolve(job)
job.handle()
ch.basic_ack(delivery_tag=method.delivery_tag)


class QueueWorkCommand(Command):
"""
Start the queue worker
queue:work
{--c|channel=default : The channel to listen on the queue}
{--f|fair : Send jobs to queues that have no jobs instead of randomly selecting a queue}
"""

def handle(self):
try:
import pika
except ImportError:
raise DriverLibraryNotFound(
"Could not find the 'pika' library. Run pip install pika to fix this.")

connection = pika.BlockingConnection(pika.URLParameters('amqp://{}:{}@{}:{}/%2F'.format(
queue.DRIVERS['amqp']['username'], queue.DRIVERS['amqp']['password'], queue.DRIVERS['amqp']['host'], queue.DRIVERS['amqp']['port'],
)))
channel = connection.channel()

channel.queue_declare(queue=self.option('channel'), durable=True)

channel.basic_consume(callback,
queue=self.option('channel'))
if self.option('fair'):
channel.basic_qos(prefetch_count=1)

self.info(' [*] Waiting to process jobs on the "{}" channel. To exit press CTRL+C'.format(
self.option('channel')))
channel.start_consuming()
2 changes: 2 additions & 0 deletions masonite/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
from .MigrateResetCommand import MigrateResetCommand
from .MigrateRollbackCommand import MigrateRollbackCommand
from .ModelCommand import ModelCommand
from .ModelDocstringCommand import ModelDocstringCommand
from .ProviderCommand import ProviderCommand
from .QueueWorkCommand import QueueWorkCommand
from .ServeCommand import ServeCommand
from .ViewCommand import ViewCommand
from .ValidatorCommand import ValidatorCommand
Expand Down
57 changes: 57 additions & 0 deletions masonite/drivers/MailLogDriver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
""" Log Driver Module """

import logging
import os

from masonite.contracts.MailContract import MailContract
from masonite.drivers.BaseMailDriver import BaseMailDriver


class MailLogDriver(BaseMailDriver, MailContract):
"""Mail log driver
"""
def __init__(self, MailConfig, View):
super().__init__(MailConfig, View)

if 'log' in MailConfig.DRIVERS and 'location' in MailConfig.DRIVERS['log']:
log_location = MailConfig.DRIVERS['log']['location']
else:
log_location = 'bootstrap/mail'

if not os.path.exists(log_location):
# Create the path to the model if it does not exist
os.makedirs(log_location)

handler = logging.FileHandler('{0}/{1}'.format(
log_location,
os.getenv('MAIL_LOGFILE', 'mail.log')
))
self.logger = logging.getLogger(__name__)
self.logger.handlers = []
self.logger.propagate = False
self.logger.addHandler(handler)
self.logger.setLevel(logging.INFO)

def send(self, message=None):
"""Prints the message in a log.
Keyword Arguments:
message {string} -- The message to be printed. (default: { None })
Returns:
None
"""

if not message:
message = self.message_body

self.logger.info('***************************************')

self.logger.info('To: {}'.format(self.to_address))
self.logger.info('From: {0} <{1}>'.format(
self.config.FROM['name'], self.config.FROM['address']))
self.logger.info('Subject: {}'.format(self.message_subject))
self.logger.info('Message: ')
self.logger.info(message)

self.logger.info('***************************************')
45 changes: 45 additions & 0 deletions masonite/drivers/MailTerminalDriver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
""" Terminal Driver Module """

import logging

from masonite.contracts.MailContract import MailContract
from masonite.drivers.BaseMailDriver import BaseMailDriver


class MailTerminalDriver(BaseMailDriver, MailContract):
"""Mail terminal driver
"""

def __init__(self, MailConfig, View):
super().__init__(MailConfig, View)

self.logger = logging.getLogger(__name__)
self.logger.handlers = []
handler = logging.StreamHandler()
self.logger.setLevel(logging.INFO)
self.logger.addHandler(handler)
self.logger.propagate = False

def send(self, message=None):
"""Prints the message to the terminal.
Keyword Arguments:
message {string} -- The message to be printed. (default: { None })
Returns:
None
"""

if not message:
message = self.message_body

self.logger.info('***************************************')

self.logger.info('To: {}'.format(self.to_address))
self.logger.info('From: {0} <{1}>'.format(
self.config.FROM['name'], self.config.FROM['address']))
self.logger.info('Subject: {}'.format(self.message_subject))
self.logger.info('Message: ')
self.logger.info(message)

self.logger.info('***************************************')
58 changes: 58 additions & 0 deletions masonite/drivers/QueueAmqpDriver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
""" Driver for AMQP support """

import pickle
import threading

from config import queue
from masonite.contracts import QueueContract
from masonite.drivers import BaseDriver
from masonite.exceptions import DriverLibraryNotFound

if 'amqp' in queue.DRIVERS:
listening_channel = queue.DRIVERS['amqp']['channel']
else:
listening_channel = 'default'


class QueueAmqpDriver(QueueContract, BaseDriver):

def __init__(self, Container):
"""Queue AMQP Driver
Arguments:
Container {masonite.app.App} -- The application container.
"""

try:
import pika
self.pika = pika
except ImportError:
raise DriverLibraryNotFound(
"Could not find the 'pika' library. Run pip install pika to fix this.")

# Start the connection
connection = self.pika.BlockingConnection(
self.pika.ConnectionParameters('localhost')
)

# Get the channel
self.channel = connection.channel()

# Declare what queue we are working with
self.channel.queue_declare(queue=listening_channel, durable=True)

def push(self, *objects):
"""Push objects onto the amqp stack.
Arguments:
objects {*args of objects} - This can be several objects as parameters into this method.
"""

for obj in objects:
# Publish to the channel for each object
self.channel.basic_publish(exchange='',
routing_key=listening_channel,
body=pickle.dumps(obj),
properties=self.pika.BasicProperties(
delivery_mode=2, # make message persistent
))
5 changes: 4 additions & 1 deletion masonite/drivers/QueueAsyncDriver.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
""" Async Driver Method """

import threading
import inspect

from masonite.contracts.QueueContract import QueueContract
from masonite.drivers.BaseDriver import BaseDriver
Expand All @@ -27,7 +28,9 @@ def push(self, *objects):
"""

for obj in objects:
obj = self.container.resolve(obj)
if inspect.isclass(obj):
obj = self.container.resolve(obj)

thread = threading.Thread(
target=obj.dispatch(), args=(), kwargs={})
thread.start()
3 changes: 3 additions & 0 deletions masonite/drivers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
from .CacheDiskDriver import CacheDiskDriver
from .MailMailgunDriver import MailMailgunDriver
from .MailSmtpDriver import MailSmtpDriver
from .MailLogDriver import MailLogDriver
from .MailTerminalDriver import MailTerminalDriver
from .QueueAsyncDriver import QueueAsyncDriver
from .QueueAmqpDriver import QueueAmqpDriver
from .SessionCookieDriver import SessionCookieDriver
from .SessionMemoryDriver import SessionMemoryDriver
from .UploadDiskDriver import UploadDiskDriver
Expand Down
2 changes: 1 addition & 1 deletion masonite/info.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Module for specifying the Masonite version in a central location.
"""

VERSION = '2.0.24'
VERSION = '2.0.25'
6 changes: 4 additions & 2 deletions masonite/providers/AppProvider.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
KeyCommand, MakeMigrationCommand,
MigrateCommand, MigrateRefreshCommand,
MigrateResetCommand, MigrateRollbackCommand,
ModelCommand, ProviderCommand, RoutesCommand,
SeedCommand, SeedRunCommand, ServeCommand,
ModelCommand, ModelDocstringCommand, ProviderCommand, RoutesCommand,
SeedCommand, SeedRunCommand, ServeCommand, QueueWorkCommand,
TinkerCommand, ViewCommand, ValidatorCommand)

from masonite.exception_handler import ExceptionHandler
Expand Down Expand Up @@ -49,7 +49,9 @@ def register(self):
self.app.bind('MasoniteMigrateRollbackCommand',
MigrateRollbackCommand())
self.app.bind('MasoniteModelCommand', ModelCommand())
self.app.bind('MasoniteModelDocstringCommand', ModelDocstringCommand())
self.app.bind('MasoniteProviderCommand', ProviderCommand())
self.app.bind('MasoniteQueueWorkCommand', QueueWorkCommand())
self.app.bind('MasoniteViewCommand', ViewCommand())
self.app.bind('MasoniteRoutesCommand', RoutesCommand())
self.app.bind('MasoniteServeCommand', ServeCommand())
Expand Down
5 changes: 4 additions & 1 deletion masonite/providers/MailProvider.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
""" A Mail Service Provider """

from config import mail
from masonite.drivers import MailMailgunDriver, MailSmtpDriver
from masonite.drivers import MailMailgunDriver, MailSmtpDriver, \
MailLogDriver, MailTerminalDriver
from masonite.managers import MailManager
from masonite.provider import ServiceProvider

Expand All @@ -14,6 +15,8 @@ def register(self):
self.app.bind('MailConfig', mail)
self.app.bind('MailSmtpDriver', MailSmtpDriver)
self.app.bind('MailMailgunDriver', MailMailgunDriver)
self.app.bind('MailLogDriver', MailLogDriver)
self.app.bind('MailTerminalDriver', MailTerminalDriver)
self.app.bind('MailManager', MailManager(self.app))

def boot(self, MailConfig, MailManager):
Expand Down
3 changes: 2 additions & 1 deletion masonite/providers/QueueProvider.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
""" A RedirectionProvider Service Provider """

from config import queue
from masonite.drivers import QueueAsyncDriver
from masonite.drivers import QueueAsyncDriver, QueueAmqpDriver
from masonite.managers import QueueManager
from masonite.provider import ServiceProvider

Expand All @@ -12,6 +12,7 @@ class QueueProvider(ServiceProvider):

def register(self):
self.app.bind('QueueAsyncDriver', QueueAsyncDriver)
self.app.bind('QueueAmqpDriver', QueueAmqpDriver)
self.app.bind('QueueManager', QueueManager)
self.app.bind('QueueConfig', queue)

Expand Down
Loading

0 comments on commit f7a08c2

Please sign in to comment.