示例#1
0
def app():
    """
    Contains app with all routes loaded from the app in test mode
    """
    app = create_app()
    app.config['TESTING'] = True
    return app
示例#2
0
文件: manage.py 项目: s2nner/py_test
def createdb(testdata=False):
    app = create_app()
    with app.app_context():
        db.drop_all()
        db.create_all()
        if testdata:
            u = User(username='******', password_hash='test')
            db.session.add(u)
            db.session.commit()
示例#3
0
    def setUp(self):

        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()

        db.create_all()

        user = User(
            username="******",
            email="*****@*****.**",
            password_hash="chiditheboss"
        )
        db.session.add(user)
        db.session.commit()

        self.client = self.app.test_client()
示例#4
0
    def setUp(self):
        # Get rid of old test DB if any
        db_filename = config.DB_FILENAME
        if os.path.isfile(db_filename):
            os.remove(db_filename)

        app = create_app(config)
        self.test_app = app.test_client()
        self.session = db.get_session()

        self.start = datetime.utcnow() - timedelta(seconds=10)
        # Add 5 aliens to the DB
        for i in range(5):
            a = models.Alien()
            a.name = 'alien_' + str(i)
            a.created = self.start + timedelta(seconds=i)
            self.session.add(a)

        self.session.commit()
    def setUp(self):

        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()

        db.drop_all()
        db.create_all()

        user = User(
            username="******",
            email="*****@*****.**",
        )
        user.hash_password("chiditheboss")
        db.session.add(user)
        db.session.commit()
        g.user = user

        self.client = self.app.test_client()
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()

        db.create_all()

        user = User(
            username="******",
            email="*****@*****.**",
            password_hash="chiditheboss"
        )
        user.hash_password("chiditheboss")
        db.session.add(user)
        db.session.commit()
        g.user = user

        bucketlist = Bucketlist(name="Awesome Bucketlist", created_by=g.user.id)
        bucketlist.save()

        self.client = self.app.test_client()
示例#7
0
#!/bin/env python
from api import create_app, x_socketio

import os
import json
import collections
import datetime
from flask import Flask, request, current_app, make_response, session, escape, Response, jsonify
from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity
from neo4j.v1 import GraphDatabase, basic_auth
from lib.crossDomain import crossdomain

import sys

app, jwt = create_app()

@jwt.expired_token_loader
@crossdomain(origin='*', attatch_to_all=True, headers=['Content-Type', 'Authorization'])
def expired_token_callback():
    resp = {
        'status': 401,
        'msg': 'The token has expired'
    }
    return Response(response=json.dumps(resp), status=200, mimetype="application/json")

@app.errorhandler(401)
@crossdomain(origin='*', attatch_to_all=True, headers=['Content-Type', 'Authorization'])
def auth_failed(e):

  resp = (("status", "err"),
          ("msg", "The request could not be completed"))
示例#8
0
 def create_app(self):
     # pass in test configuration
     app = create_app(TestConfig)
     return app
def app(request):
    app = create_app('flask_config.TestingConfig')
    app = app.test_client()
    return app
示例#10
0
from api import create_app

if __name__ == "__main__":
    app = create_app("flask_config.DevelopmentConfig")
    app.run(debug=True)
示例#11
0
import unittest
import json
from api import create_app, db
from api.config import app_config
from api.blogs.models import User

app = create_app()


class AuthTestCase(unittest.TestCase):
    """This represents the authentication testcase"""

    def setUp(self):
        # binds the app to the current context
        self.client = app.test_client()
        self.user = {
            'username': '******',
            'email': '*****@*****.**',
            'password': '******'}
        with app.app_context():
            # create all database tables
            db.create_all()
    def test_successful_registration(self):
        """Test when user registers with right credentials"""
        res = self.client.post('/api/v1/auth/register', data=self.user)
        self.assertEqual(res.status_code, 201)

    def test_already_registered_user(self):
        """Test that a user cannot be registered twice."""
        res = self.client.post('/api/v1/auth/register',data=self.user)
        second_res = self.client.post('/api/v1/auth/register',
示例#12
0
def test_config():
    """Test create_app without passing test config."""
    assert not create_app().testing
    assert create_app({'TESTING': True}).testing
示例#13
0
            keypath=args.keypath,
            protocol=args.proto,
            server_number=args.server,
        )
        print(sid, end="")
    except Exception as e:
        print(e, file=sys.stderr)
        print("ERROR: failed to load shell server", file=sys.stderr)
        exit(1)


if __name__ == '__main__':

    parser = argparse.ArgumentParser(description="Add Shell Server")

    parser.add_argument("-n", "--name", required=True)
    parser.add_argument("-u", "--user", required=True)
    parser.add_argument("-k", "--keypath", required=True)
    parser.add_argument("--host", required=True)
    parser.add_argument("--proto", required=True)
    parser.add_argument("--port", default="22")
    parser.add_argument("--server", default="1")

    args = parser.parse_args()

    # set default picoCTF settings
    if 'APP_SETTINGS_FILE' not in os.environ:
        os.environ['APP_SETTINGS_FILE'] = '/picoCTF-web-config/deploy_settings.py'
    with api.create_app().app_context():
        main(args)
示例#14
0
 def _pre_setup(self):
     self.app = api.create_app(config=test_settings)
     self.client = self.app.test_client()
     self._ctx = self.app.test_request_context()
     self._ctx.push()
示例#15
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask_script import Manager, Shell, Server
from flask_script.commands import Clean, ShowUrls, Command
from flask_migrate import MigrateCommand

from api import create_app
from api.v1.models import User, Role, roles_users, user_datastore, Cookie
from api.v1.settings import DevConfig, ProdConfig
from api import db

if os.environ.get("API_ENV") == "prod":
    app = create_app(ProdConfig)
else:
    app = create_app(DevConfig)

HERE = os.path.abspath(os.path.dirname(__file__))
TEST_PATH = os.path.join(HERE, "api/v1/tests")

manager = Manager(app)


def _make_context():
    """Return context dict for a shell session so you can access
    app, db, and the User model by default.
    """
    return {"app": app, "db": db, "User": User}


@manager.command
示例#16
0
 def setUp(self):
     self.app = create_app()
     self.health = Health()
示例#17
0
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)

from api import create_app
app = application = create_app('flask_config.ProductionConfig')
application.secret_key = 'Add your secret key'
示例#18
0
文件: wsgi.py 项目: zmingee/flaskell
# -*- coding: utf-8 -*-
"""
This module provides an entrypoint for WSGI servers, accessible by ``application``
or by running this file as a script.

This module is not currently using the :class:`werkzeug.wsgi.DispatcherMiddleware`
as there is not a need for it in this case. There is only one "app",
:module:`{{cookiecutter.repo_name}}.api`, so there is no need to have the functionality for
more to be added. This can be changed easily by using the commented-out sections
of this module.
"""

from werkzeug.serving import run_simple
#from werkzeug.wsgi import DispatcherMiddleware

from {{cookiecutter.repo_name}} import api

#application = DispatcherMiddleware(frontend.create_app(), {
#    '/api': api.create_app()
#})

APPLICATION = api.create_app()

if __name__ == "__main__":
    run_simple('0.0.0.0', 5000, APPLICATION, use_reloader=True, use_debugger=True)
示例#19
0
 def setUp(self):
     self.app = create_app()
     self.test_client = self.app.test_client()
示例#20
0
import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from api import db, create_app
from api.models.user import User
from api.models.business import Business
from api.models.review import Review
from api.models.category import Category
from api.models.blacklisted_tokens import BlacklistedToken

app = create_app(config_name='production')
migrate = Migrate(app, db)
manager = Manager(app)

manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
示例#21
0
from api import create_app
from commands import create_manager
import config

if __name__ == '__main__':
    manager = create_manager(create_app(config))
    manager.run()
示例#22
0
 def setUp(self):
     '''
         Set up test data
     '''
     self.main = create_app('testing')
     self.app = self.main.test_client()
     self.app_context = self.main.app_context()
     self.app_context.push()
     with self.app_context:
         db.init_app(self.main)
         db.create_all()
     self.sample_user = {
         'username': '******',
         'email': '*****@*****.**',
         'password': '******',
         'confirm_password': '******'
     }
     self.exist_user = {
         'username': '******',
         'email': '*****@*****.**',
         'password': '******',
         'confirm_password': '******'
     }
     self.unconfirmed_user = {
         'username': '******',
         'email': '*****@*****.**',
         'password': '******',
         'confirm_password': '******',
         'activation_token': 'AvauDT0T7wo_O6vnb5XJxKzuPteTIpJVv_0HRokS'
     }
     self.business_data = {
         'name': 'Inzora rooftop coffee',
         'description': 'We have best coffee for you,',
         'category': 'Coffee-shop',
         'country': 'Kenya',
         'city': 'Nairobi'
     }
     # Business sample data
     self.rev_business_data = {
         'name': 'KFC',
         'description': 'Finger lickin\' good',
         'category': 'Food',
         'country': 'Kenya',
         'city': 'Nairobi'
     }
     with self.main.test_request_context():
         # Orphan id: User id that will be used to create an orphan token
         orphan_user = User(username="******",
                            email="*****@*****.**",
                            password=self.sample_user['password'])
         user = User(username=self.sample_user['username'],
                     email=self.sample_user['email'],
                     password=generate_password_hash(
                         self.sample_user['password']),
                     activation_token=None)
         unconfirmed_account = User(
             username=self.unconfirmed_user['username'],
             email=self.unconfirmed_user['email'],
             password=generate_password_hash(
                 self.unconfirmed_user['password']),
             activation_token=self.unconfirmed_user['activation_token'])
         db.session.add(user)
         db.session.add(orphan_user)
         db.session.add(unconfirmed_account)
         db.session.commit()
         self.sample_user['id'] = user.id
         self.orphan_id = orphan_user.id
         self.unconfirmed_user_id = unconfirmed_account.id
         db.session.remove()
         token = Token(user_id=self.sample_user['id'],
                       access_token=get_token(self.sample_user['id']))
         orphan_token = Token(user_id=self.orphan_id,
                              access_token=get_token(self.orphan_id))
         unconfirmed_user_token = Token(user_id=self.unconfirmed_user_id,
                                        access_token=get_token(
                                            self.unconfirmed_user_id))
         expired_token = Token(user_id=self.sample_user['id'],
                               access_token=get_token(
                                   self.sample_user['id'], -3600))
         # Create bad signature token
         # Bad signature: #nt secret key from the one used in our API used
         # to hash tokens
         other_signature_token = Token(user_id=self.sample_user['id'],
                                       access_token=get_token(
                                           self.sample_user['id'], 3600,
                                           'other_signature'))
         business = Business(
             user_id=self.sample_user['id'],
             name=self.rev_business_data['name'],
             description=self.rev_business_data['description'],
             category=self.rev_business_data['category'],
             country=self.rev_business_data['country'],
             city=self.rev_business_data['city'],
         )
         db.session.add(token)
         db.session.add(orphan_token)
         db.session.add(expired_token)
         db.session.add(unconfirmed_user_token)
         db.session.add(other_signature_token)
         db.session.add(business)
         db.session.commit()
         self.test_token = token.access_token
         self.expired_test_token = expired_token.access_token
         self.other_signature_token = other_signature_token.access_token
         self.orphan_token = orphan_token.access_token
         self.unconfirmed_user_token = unconfirmed_user_token.access_token
示例#23
0
 def create_app(self):
     app = create_app(TestConfig())
     self.twill = Twill(app, port=3000)
     return app
示例#24
0
import os
from api import create_app

app = create_app(os.getenv('FLASK_ENV'))
示例#25
0
文件: run.py 项目: s2nner/py_test
from api import create_app


app = create_app()

if __name__ == "__main__":

    app.run(host=app.config['HOST'], port=app.config['PORT'])
示例#26
0
import api

app = api.create_app()
示例#27
0
from api import db, create_app
db.create_all(app=create_app())
示例#28
0
#! /usr/bin/env python
import os
from flask import jsonify
from flask.ext.script import Manager, Shell, Command, Server
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.security.datastore import SQLAlchemyUserDatastore
from flask.ext.security import Security, auth_token_required
from flask_security.utils import encrypt_password
from sqlalchemy.exc import IntegrityError


from api import create_app, db
from api.models import User, Role
# from . import create_app, db

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)


def make_shell_context():
    return dict(app=app, db=db)


class DBInit(Command):
    ''' Creates tables from SQLAlchemy models. '''
示例#29
0
 def setUp(self):
     self.test_app = create_app({'TESTING': True})
     self.test_request = self.test_app.test_client()
     with self.test_app.app_context():
         self.req_db = RequestHelper.req_db
示例#30
0
文件: wsgi.py 项目: cfchase/modh-demo
import os
from api import create_app

application = create_app(__name__)

if __name__ == "__main__":
    host = os.getenv('HOST') or '0.0.0.0'
    port = os.getenv('PORT') or '8080'
    application.run(host=host, port=port)


@application.shell_context_processor
def make_shell_context():
    return {}
示例#31
0
 def start_flask():
     app = create_app(chimera_config=True)
     app.run(host='0.0.0.0', port=5000)
示例#32
0
from api import create_app, socketio

app = create_app(debug=True)

if __name__ == '__main__':
    socketio.run(app, debug=True, port=5000, host='0.0.0.0')
示例#33
0
 def setUp(self):
     self.app = create_app('testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
示例#34
0
def client():
    app = create_app()
    app.config['TESTING'] = True
    app.testing = True

    return app.test_client()
示例#35
0
        # Configure gunicorn
        workers = int(os.environ.get('MAX_PROCESSES'))
        bind = '%s:%s' % (
            os.environ.get('SERVER_HOST'),
            os.environ.get('SERVER_PORT')
        )
        logconfig = 'logger.conf'
        access_log_format = '%(h)s ** %(m)s: %(U)s ** QUERY: %(q)s ** <%(s)s>'

        # TO-DO
        # Starting gunicorn server


class WSGIServer(Command):

    def run(self):
        app.run(
            host=app.config.get('SERVER_HOST'),
            port=app.config.get('SERVER_PORT'),
            processes=app.config.get('MAX_PROCESSES'),
        )

app = create_app(os.environ.get('CONFIG_MODE', 'DEFAULT'))
manager = Manager(app)
manager.add_command('init', Init())
manager.add_command('runserver', WSGIServer())
manager.add_command('rungunicorn', Gunicorn())

if __name__ == '__main__':
    manager.run()
示例#36
0
# -*- coding: utf-8 -*-
__author__ = 'florije'
import os

from flask.ext.script import Manager, Shell, Server
from flask.ext.migrate import Migrate, MigrateCommand

from api import create_app
from api.models import db
from api.models import TaskModel


app = create_app(os.getenv('FLASK_CONFIG') or 'development')

manager = Manager(app)
manager.add_command("runserver", Server())
manager.add_command("shell", Shell())

migrate = Migrate(app, db)


def make_shell_context():
    return dict(app=app, db=db, TaskModel=TaskModel)


manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)


@manager.command
def create_db():
示例#37
0
    max_workers = config_ini.getint('General', 'max_api_workers', fallback=0)
    log_when = config_ini.get('General', 'log_when', fallback='D')
    log_interval = config_ini.getint('General', 'log_interval', fallback=7)
    log_counter = config_ini.getint('General', 'log_counter', fallback=53)
else:
    sys.exit(1)

# **********************************************************************
# SPECIFIC APPLICATION FOLDER DIFFERS FROM APPLICATIONS
#from    api                 import create_app,db,mail,logger
from api import create_app, db, logger
# **********************************************************************
C = Context("Butler API", config_file, logger)
C.Set()

app = create_app(config_file, os.getenv('BUTLER_CONFIG') or 'production', C)

# CONFIGURATION PATCH !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

logger.name = "Butler API"
# Setup logger handlers
# Actual File system all logger ----------------------------------------
file_handler = add_Logging_Handler(logger=logger,
                                   level=C.log_level,
                                   folder=C.log_folder,
                                   nameFormat="%s.log" %
                                   logger.name.replace(' ', '_'),
                                   handlerType='TIME_ROTATING',
                                   when=log_when,
                                   interval=log_interval,
                                   backupCount=log_counter)
 def create_app(self):
     self.app = create_app('testing')
     return self.app
示例#39
0
def app():
    app = create_app()
    app.debug = True
    return app
示例#40
0
from flask_script import Manager

from api import create_app

app = create_app('development')

manager = Manager(app)

@manager.command
def migrate():
    #migration script
    pass

if __name__ == '__main__':
    manager.run()
示例#41
0
文件: run.py 项目: Nvor/MooMooBeenz
import os

from api import create_app

app = create_app(os.getenv("FLASK_ENV", "development"))

if __name__ == '__main__':
    app.run(debug=True)
示例#42
0
#!/usr/bin/env python
import os

from flask.ext.script import Manager, Server, Shell, Manager
from api import create_app
from sqlalchemy.orm import (contains_eager, joinedload, subqueryload,
        subqueryload_all, joinedload_all, defer, undefer)
from sqlalchemy import (and_, or_, Table)

from api.core.database import Base, engine, session, Session
from api.models import *

env = os.environ.get('APPNAME_ENV', 'dev')
app = create_app('api.settings.%sConfig' % env.capitalize(), env=env)

manager = Manager(app)
manager.add_command('server', Server())

def walk_subclasses(cls, subclasses=None):

    if subclasses == None:
        subclasses = {}

    for subclass in cls.__subclasses__():
        subclasses[subclass.__name__] = subclass
        walk_subclasses(subclass, subclasses=subclasses)

    return subclasses

def _make_context():
    # we may want to add additional things
 def create_app(self):
     app = create_app()
     app.testing = True
     app.config['LIVESERVER_PORT'] = 0
     app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
     return app
示例#44
0

def run_server(app):

    # Enable WSGI access logging via Paste
    app_logged = TransLogger(app)

    # Mount the WSGI callable object (app) on the root directory
    cherrypy.tree.graft(app_logged, '/')

    # Set the configuration of the web server
    cherrypy.config.update({
        'engine.autoreload.on': True,
        'log.screen': True,
        'server.socket_port': 5432,
        'server.socket_host': '0.0.0.0'
    })

    # Start the CherryPy WSGI web server
    cherrypy.engine.start()
    cherrypy.engine.block()


if __name__ == "__main__":
    # Init spark context and load libraries
    sc = init_spark_context()
    api_app = create_app(sc)

    # start web server
    run_server(api_app)
示例#45
0
 def __init__(self):
     self.app = create_app()
     self.client = self.app.test_client()
     self.twilio_client = TwilioClient(
         self.app.config['SECRETS'].TWILIO_ACCOUNT_SID,
         self.app.config['SECRETS'].TWILIO_AUTH_TOKEN)
示例#46
0
 def setUp(self):
     self.app = create_app('testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     self.client = self.app.test_client()
示例#47
0
import os

from api import create_app

# Create an application instance that web servers can use. We store it as
# "application" (the wsgi default) and also the much shorter and convenient
# "app".
application = app = create_app(os.environ.get('FLACK_CONFIG', 'production'))

示例#48
0
import os

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

from api import create_app, db

application = create_app(os.getenv('FLASK_CONFIG') or 'default')

migrate = Migrate(application, db)

manager = Manager(application)
manager.add_command('db', MigrateCommand)


@manager.command
def test():
    """Run the unit tests."""
    import unittest

    tests = unittest.TestLoader().discover('api/tests')
    unittest.TextTestRunner(verbosity=2).run(tests)


@manager.command
def recreate_db():
    """
    Recreates a local database. Drops and creates a new database
    """
    db.drop_all()
    db.create_all()
示例#49
0
"""
    Main file to run the app
"""
import os
from flask import jsonify, redirect
from api import create_app
from api.models import db
from flask_migrate import Migrate
from flask_mail import Mail
# Init Flask mail
mail = Mail()
APP = create_app(os.getenv('ENV'))
migrate = Migrate(APP, db)


@APP.errorhandler(404)
def not_found(error):
    """
        Return json error if page not found
    """
    return jsonify({
        'status': 'error',
        'message': 'Page not found'
    }), 404


@APP.errorhandler(400)
def bad_request(e):
    """
        Bad request json response
    """
示例#50
0
 def create_app(self):
     app = create_app()
     app.config.from_object(TestConfig)
     return app
示例#51
0
from api import create_app

if __name__ == '__main__':
    create_app()
 def setUp(self):
     self.app = create_app(environment="Testing")
示例#53
0
import os
from api import create_app
config_name = os.getenv('APP_ENVIRONMENT')
app = create_app(config_name)

if __name__ == "__main__":
    app.run()
示例#54
0
from api import create_app

application = create_app()

if __name__ == '__main__':
    application.run()
示例#55
0
 def setUp(self):
     self.app = create_app(environment="Testing")
示例#56
0
#! /usr/bin/env python
import os
from flask import request, jsonify, session
from flask.ext.script import Manager, Shell, Command, Server
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.login import login_required

from api import create_app, db
from api.models import User

# from . import create_app, db

app = create_app(os.getenv("FLASK_CONFIG") or "default")
manager = Manager(app)
migrate = Migrate(app, db)


def make_shell_context():
    return dict(app=app, db=db)


class DBInit(Command):
    """ Creates tables from SQLAlchemy models. """

    def __init__(self, db):
        self.db = db

    def run(self):
        self.db.create_all()

示例#57
0
from decouple import config as env_config
from api import create_app
from flask_script import Manager

app = create_app(env_config('ENV'))
manager = Manager(app)


@manager.command
def run_server():
    app.run(env_config('HOST'), port=5500, debug=True)


if __name__ == "__main__":
    manager.run()
示例#58
0
from api import create_app
from db import database_setup, create_schema

is_production = settings.ENV == "production"
if is_production:
    googleclouddebugger.enable()

echo = False if is_production else True
session = database_setup(settings.DB_API,
                         settings.DB_USERNAME,
                         settings.DB_PASSWORD,
                         settings.DB_NAME,
                         settings.DB_CONN_NAME,
                         echo=echo)

app = create_app(session)

if __name__ == "__main__":
    args = docopt(__doc__)
    if args["create_schema"]:
        create_schema(settings.DB_API,
                      settings.DB_USERNAME,
                      settings.DB_PASSWORD,
                      settings.DB_NAME,
                      settings.DB_CONN_NAME,
                      echo=echo)

    if args["populate"]:
        storage_client = storage.Client()
        exercism.populate_python(session, storage_client,
                                 settings.BUCKET_EXERCISES)
示例#59
0
文件: images_test.py 项目: xmm/fstore
 def create_app(self):
     return create_app(environment='testing')