Beispiel #1
0
def jinja_email(template_path, context, version, language=None):

    base_url = settings.get("email.url")
    paths = settings.get("email.paths")[version]

    lang = language
    if lang is None:
        lang = settings.get("language", "en")

    def get_url(path, query=None):
        querystring = ""
        if query:
            querystring = "?" + urlencode(query)
        return "{}/{}{}".format(base_url, paths[path], querystring)

    def translate(key, language=None, *args, **kwargs):
        return settings.translate(language or lang, key, *args, **kwargs)

    # we set up the jinja environment with the template directories
    template_paths = settings.get("email.template_paths")
    jinja_env = Environment(loader=TemplateLoader(template_paths))
    jinja_env.filters["translate"] = translate
    jinja_env.filters["url"] = get_url

    c = {"language": lang, "version": version}

    c.update(settings.get("email.context"))
    c.update(context)

    template = jinja_env.get_template(template_path)
    module = template.make_module(c)
    return module
Beispiel #2
0
def run_api():
    """
    Run the API server.
    """
    app = get_app(settings)
    o = urlparse(settings.get("url"))
    if o.port:
        host = o.netloc.split(":")[0]
    else:
        host = o.netloc
    app.run(debug=settings.get("debug", True),
            host=host,
            port=o.port,
            threaded=False)
Beispiel #3
0
    def setUpClass(self):

        super(ApiTest, self).setUpClass()

        # we initialize the settings...
        settings.set(
            "url",
            "{}://{}:{}{}".format(self.protocol, self.host, self.port,
                                  self.api_base_url),
        )
        settings.initialize()

        if not settings.get("test"):
            raise AttributeError(
                "You try to run tests in a non-test environment!")

        self.test_queue = multiprocessing.Queue()
        self.api_process = ApplicationProcess(self.host,
                                              self.port,
                                              get_app(settings),
                                              settings,
                                              queue=self.test_queue)
        self.api_process.start()

        self.settings = settings
        self.app = get_app(settings)
        self.client = self.app.test_client()

        # this parameter might need some tuning to be sure the API is up when the tests start
        time.sleep(0.3)
Beispiel #4
0
    def add_crossdomain_headers(self, response):

        opts = settings.get("crossdomain")
        if not opts or not opts.get("enabled", False):
            return

        def origin_allowed(origin, allowed_origins):
            for allowed_origin in allowed_origins:
                if re.match(allowed_origin, origin):
                    return True
            return False

        origin = request.headers.get("Origin")

        if not origin or not origin_allowed(origin, opts.get("origins", [])):
            return

        # we add cross-domain headers
        response.headers["Access-Control-Allow-Origin"] = origin
        # we allow all methods that are defined in the class
        response.headers["Access-Control-Allow-Methods"] = ", ".join([
            method for method in ("GET", "POST", "PUT", "PATCH", "DELETE")
            if hasattr(self, method.lower())
        ])
        response.headers["Access-Control-Max-Age"] = str(
            opts.get("max-age", 120))
        response.headers["Access-Control-Allow-Headers"] = request.headers.get(
            "Access-Control-Request-Headers",
            ", ".join(opts.get("allowed-headers", [])))
Beispiel #5
0
    def setUp(self):

        if not settings.get("test"):
            raise AttributeError(
                "You try to run tests in a non-TEST environment!")

        self.session.rollback()
        self.initialize_fixtures()
Beispiel #6
0
def send_email(to, subject, text=None, html=None, config=None):

    logger.info("Sending an e-mail...")

    if config is None:
        config = settings.get("smtp")

    if text is None and html is None:
        raise ValueError("text or html (or both) needs to be defined!")

    sender_name = settings.get("name", "[No-Name]")

    msg = MIMEMultipart("alternative")
    msg["From"] = config["from"]
    msg["To"] = to
    msg["Subject"] = Header(subject, "utf-8")
    msg["Date"] = format_datetime(datetime.datetime.utcnow())

    if text:
        msg.attach(MIMEText(text, "plain", "utf-8"))
    if html:
        msg.attach(MIMEText(html, "html", "utf-8"))

    if settings.get("test"):
        if hasattr(settings, "test_queue"):
            settings.test_queue.put({"type": "email", "data": msg})
        return msg

    try:
        if config.get("ssl"):
            smtp = smtplib.SMTP_SSL(config["server"], config["port"])
        else:
            smtp = smtplib.SMTP(config["server"], config["port"])
        smtp.ehlo()
        if config.get("tls"):
            smtp.starttls()
        smtp.ehlo()
        smtp.login(config["username"], config["password"])
        smtp.sendmail(msg["From"], msg["To"], msg.as_string().encode("ascii"))
        smtp.quit()
        logger.info("Successfully sent e-mail.")
    except:
        logger.error("Could not send e-mail:", traceback.format_exc())
Beispiel #7
0
    def setUpClass(cls):

        super(MockApiTest, cls).setUpClass()

        if not settings.get("test"):
            raise AttributeError(
                "You try to run tests in a non-TEST environment!")

        cls.settings = settings
        cls.app = get_app(settings).test_client()
        cls.app.testing = True
Beispiel #8
0
def main():
    if not settings_filenames:
        sys.stderr.write(
            "Error, no settings defined, aborting. Please define your settings"
            " directory using ALGONAUT_SETTINGS_D environment variable.\n"
        )
        exit(-1)
    for plugin in settings.get("plugins", {}):
        config = settings.load_plugin_config(plugin)
        if "commands" in config:
            for command in config["commands"]:
                algonaut.add_command(command)
    algonaut()
Beispiel #9
0
def _clean_db(settings, plugin):
    with settings.session() as session:
        if plugin is None:
            plugins = list(settings.get("plugins", {}).keys()) + ["core"]
        else:
            plugins = [plugin]
        for plugin in plugins:
            if plugin == "core":
                clean_db(session)
                continue
            config = settings.load_plugin_config(plugin)
            if "clean_db" in config:
                config["clean_db"](session)
Beispiel #10
0
def initialize_rabbitmq():
    """
    Initializes the local RabbitMQ node. This only works for a locally running
    RabbitMQ instance.
    """
    script = """#!/bin/bash
    #reset all currently active tasks
    rabbitmqctl stop_app
    rabbitmqctl reset
    rabbitmqctl start_app

    #set the time-to-live policy of the messages
    rabbitmqctl set_policy TTL ".*" '{{"message-ttl":1200000}}' --apply-to queues
    #delete the guest user
    rabbitmqctl delete_user guest
    #create virtualhost algonaut
    rabbitmqctl add_vhost {vhost}
    #create user
    rabbitmqctl add_user {user} {password}
    #grant all permission to user on virtualhost
    rabbitmqctl set_permissions -p {vhost} {user} ".*" ".*" ".*"
    echo "Done"
"""
    broker_url = settings.get("worker.config.broker_url", "")
    match = re.match(
        r"^amqp://([\w\d\-]+):([\w\d\-]+)@([\w\d\.\-]+):(\d+)/([\w\d\-]+)$", broker_url
    )
    if not match:
        print("Invalid Broker URL!")
        exit(-1)
    user, password, hostname, port, vhost = match.groups()
    if hostname not in ("localhost", "127.0.0.1"):
        print("This script only works for a locally installed RabbitMQ instance")
        exit(0)
    file, filename = tempfile.mkstemp(suffix=".sh")
    os.write(
        file, script.format(vhost=vhost, user=user, password=password).encode("utf-8")
    )
    os.close(file)
    os.chmod(filename, 700)
    p = subprocess.Popen([filename])
    p.wait()
Beispiel #11
0
from algonaut.settings import settings
from .app import get_app

settings.setup_logging(settings.get("loglevel", 4))
settings.initialize()
app = get_app(settings)
Beispiel #12
0
def send(data):
    email = settings.get('contact-form.email')
    if not email:
        return
    send_email(to=email, subject='New contact form', text=str(data))
Beispiel #13
0
 def migrate_plugins():
     for plugin_name, plugin_params in settings.get("plugins").items():
         migrate_plugin(plugin_name)