コード例 #1
0
    def setUp(self):
        self.app = Flask(__name__)
        self.autodoc = Autodoc(self.app)

        @self.app.route('/')
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        self.client = self.app.test_client()
コード例 #2
0
def create_app():
    auto = Autodoc(app)
    cal = Calendar()
    event = Event()
    from open_event.views.views import app as routes
    app.register_blueprint(routes)
    migrate = Migrate(app, db)

    db.init_app(app)
    manager = Manager(app)
    manager.add_command('db', MigrateCommand)

    cors = CORS(app)
    app.secret_key = 'super secret key'
    app.config.from_object('config.ProductionConfig')
    # app.config.from_object('config.LocalSQLITEConfig')
    app.config['UPLOADS_FOLDER'] = os.path.realpath('.') + '/static/'
    app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'
    app.config['STATIC_URL'] = '/static/'
    app.config['STATIC_ROOT'] = 'staticfiles'
    app.config['STATICFILES_DIRS'] = (os.path.join(BASE_DIR, 'static'), )
    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    app.logger.setLevel(logging.INFO)
    # logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

    admin_view = AdminView("Open Event")
    admin_view.init(app)
    admin_view.init_login(app)

    return app, manager, db
コード例 #3
0
class TestAutodocWithFlask(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.autodoc = Autodoc(self.app)

        @self.app.route('/')
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        self.client = self.app.test_client()

    def test_html(self):
        @self.app.route('/docs')
        def html_docs():
            return self.autodoc.html()

        response = self.client.get('/docs')
        self.assertEqual(response.status_code, 200)

    def test_json(self):
        @self.app.route('/docs')
        def json_docs():
            return self.autodoc.json()

        response = self.client.get('/docs')
        self.assertEqual(response.status_code, 200)

        data = json.loads(response.data.decode('utf-8'))
        self.assertIn('endpoints', data)
        self.assertEqual(len(data['endpoints']), 1)

        endpoint = data['endpoints'][0]
        expected = {
            "args": [],
            "docstring": "Returns a hello world message",
            "methods": ["GET", "HEAD", "OPTIONS"],
            "rule": "/"
        }
        self.assertEqual(endpoint, expected)
コード例 #4
0
def create_app():
    auto = Autodoc(app)
    cal = Calendar()
    event = Event()

    app.register_blueprint(api_v1_routes)
    migrate = Migrate(app, db)

    app.config.from_object(environ.get('APP_CONFIG',
                                       'config.ProductionConfig'))
    db.init_app(app)
    manager = Manager(app)
    manager.add_command('db', MigrateCommand)

    cors = CORS(app)
    app.secret_key = 'super secret key'
    app.config['UPLOADS_FOLDER'] = os.path.realpath('.') + '/static/'
    app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'
    app.config['STATIC_URL'] = '/static/'
    app.config['STATIC_ROOT'] = 'staticfiles'
    app.config['STATICFILES_DIRS'] = (os.path.join(BASE_DIR, 'static'), )
    app.config['SQLALCHEMY_RECORD_QUERIES'] = True
    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    app.logger.setLevel(logging.INFO)
    app.jinja_env.add_extension('jinja2.ext.do')
    app.jinja_env.add_extension('jinja2.ext.loopcontrols')
    app.jinja_env.undefined = SilentUndefined
    app.jinja_env.filters['operation_name'] = operation_name
    # logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

    # set up jwt
    app.config['JWT_AUTH_USERNAME_KEY'] = 'email'
    app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=24 * 60 * 60)
    app.config['JWT_AUTH_URL_RULE'] = None
    jwt = JWT(app, jwt_authenticate, jwt_identity)

    HTMLMIN(app)
    admin_view = AdminView("Open Event")
    admin_view.init(app)
    admin_view.init_login(app)

    # API version 2
    with app.app_context():
        from open_event.api import api_v2
        app.register_blueprint(api_v2)

    sa.orm.configure_mappers()

    return app, manager, db, jwt
コード例 #5
0
from flask import current_app, Blueprint, render_template, jsonify
doc = Blueprint("doc", __name__)

from flask_login import login_required, current_user
from flask import request, make_response, g, abort
from ..models.roles import Roles
import json, hashlib, re

# functions that require documentation need only to import doc.autodoc and
# call decorator @doc.autodoc.doc()
from flask.ext.autodoc import Autodoc
autodoc = Autodoc()

@doc.route("/")
@login_required
def documentation():
    # dict: autodoc.generate()
    data = autodoc.generate()
    result = {}     # indexed by docstring attribute hash
                    # where each entry has 'endpoint', 'docstring', 'urls'
                    # and each url has 'methods' and 'rule' attributes
    req = ["endpoint", "docstring", "methods", "rule"]
    for d in data:
        valid_doc = True
        for r in req: 
            if r not in d: valid_doc = False
        if not valid_doc: continue
        if d["docstring"] is None: continue
        key = hashlib.md5(d["docstring"]).hexdigest()
        if key not in result: 
コード例 #6
0
 def setUp(self):
     self.app = Flask(__name__)
     self.app.debug = True
     self.autodoc = Autodoc(self.app)
コード例 #7
0
class TestAutodoc(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.app.debug = True
        self.autodoc = Autodoc(self.app)

    def testGet(self):
        @self.app.route("/")
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return "Hello World!"

        with self.app.app_context():
            doc = self.autodoc.generate()
        self.assertTrue(len(doc) == 1)
        d = doc[0]
        self.assertIn('GET', d['methods'])
        self.assertNotIn('POST', d['methods'])
        self.assertEqual(d['rule'], '/')
        self.assertEqual(d['endpoint'], 'index')
        self.assertEqual(d['docstring'], "Returns a hello world message")
        self.assertFalse(d['defaults'])

    def testPost(self):
        @self.app.route("/", methods=['POST'])
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return "Hello World!"

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 1)
            d = doc[0]
            self.assertIn('POST', d['methods'])
            self.assertNotIn('GET', d['methods'])
            self.assertEqual(d['rule'], '/')
            self.assertEqual(d['endpoint'], 'index')
            self.assertEqual(d['docstring'], "Returns a hello world message")
            self.assertFalse(d['defaults'])

    def testParams(self):
        @self.app.route("/p1/p2", defaults={'param1': 'a', 'param2': 'b'})
        @self.app.route("/p1/<string:param1>/p2/<int:param2>")
        @self.autodoc.doc()
        def ab(param1, param2):
            return "param1=%s param2=%2" % (param1, param2)

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 2)

            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertTrue("/p1/p2" in rules)
            self.assertTrue("/p1/<string:param1>/p2/<int:param2>" in rules)

            for d in doc:
                self.assertEqual(d['endpoint'], 'ab')
                self.assertIsNone(d['docstring'])

                if "/p1/p2" in d['rule']:
                    self.assertDictEqual(d['defaults'], {
                        'param2': 'b',
                        'param1': 'a'
                    })
                elif "/p1/<string:param1>/p2/<int:param2>" in d['rule']:
                    self.assertFalse(d['defaults'])

    def testGroup(self):
        @self.app.route("/pri")
        @self.autodoc.doc("private")
        def pri():
            return "This is a private endpoint"

        @self.app.route("/pub")
        @self.autodoc.doc("public")
        def pub():
            return "This is a public endpoint"

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 2)

            doc = self.autodoc.generate("all")
            self.assertTrue(len(doc) == 2)

            doc = self.autodoc.generate("private")
            self.assertTrue(len(doc) == 1)
            self.assertIn("/pri", doc[0]['rule'])

            doc = self.autodoc.generate("public")
            self.assertTrue(len(doc) == 1)
            self.assertIn("/pub", doc[0]['rule'])

    def testGroups(self):
        @self.app.route("/a")
        @self.autodoc.doc()
        def a():
            return "Hello world, a!"

        @self.app.route("/b")
        @self.autodoc.doc(groups=["group1", "group2"])
        def b():
            return "Hello world, b!"

        @self.app.route("/c")
        @self.autodoc.doc("group2")
        def c():
            return "Hello world, c!"

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 3)

            doc = self.autodoc.generate("all")
            self.assertTrue(len(doc) == 3)

            doc = self.autodoc.generate("group1")
            self.assertTrue(len(doc) == 1)
            self.assertIn("/b", doc[0]['rule'])

            doc = self.autodoc.generate("group2")
            self.assertTrue(len(doc) == 2)
            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertIn("/b", rules)
            self.assertIn("/c", rules)

            doc = self.autodoc.generate(groups=["group2"])
            self.assertTrue(len(doc) == 2)
            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertIn("/b", rules)
            self.assertIn("/c", rules)

    def testHTML(self):
        @self.app.route("/")
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return "Hello World!"

        with self.app.app_context():
            doc = self.autodoc.html()
            self.assertIn("/", doc)
            self.assertIn("Returns a hello world message", doc)

    def testHTMLWithArgs(self):
        @self.app.route("/p1/p2", defaults={'param1': 'a', 'param2': 'b'})
        @self.app.route("/p1/<string:param1>/p2/<int:param2>")
        @self.autodoc.doc()
        def ab(param1, param2):
            """Returns arguments

            This endpoint returns the value of the 2 parameters:
            - param1
            - param2
            """
            return "param1=%s param2=%2" % (param1, param2)

        with self.app.app_context():
            doc = self.autodoc.html(title="hello")
            self.assertIn("/p1/p2", doc)
            self.assertRegexpMatches(
                doc, "\/p1\/.*string:param1.*\/p2\/.*int:param2.*")
            self.assertIn("Returns arguments", doc)
コード例 #8
0
from ..helpers.data_getter import DataGetter
from ..helpers.data import save_to_db, uploaded_file_provided_by_url
from views_helpers import event_status_code, api_response
from flask import Blueprint
from flask.ext.autodoc import Autodoc
from icalendar import Calendar
import icalendar
from app.helpers.oauth import OAuth, FbOAuth, InstagramOAuth, TwitterOAuth
from requests.exceptions import HTTPError
from ..helpers.data import get_google_auth, create_user_oauth, get_facebook_auth, user_logged_in, get_instagram_auth
import geoip2.database
import time
import json
from app.helpers.storage import upload, UploadedFile

auto = Autodoc()

app = Blueprint('', __name__)


@app.route('/api/v1/event', methods=['GET'])
@auto.doc()
@cross_origin()
def get_events():
    """Returns all events"""
    return ObjectFormatter.get_json("events", Event.query, request)


@app.route('/api/v1/event/page/<int:page>', methods=['GET'])
@auto.doc()
@cross_origin()
コード例 #9
0
 def setUp(self):
     self.app = Flask(__name__)
     self.app.debug = True
     self.autodoc = Autodoc(self.app)
コード例 #10
0
class TestAutodoc(unittest.TestCase):

    def setUp(self):
        self.app = Flask(__name__)
        self.app.debug = True
        self.autodoc = Autodoc(self.app)

    @staticmethod
    def thisFile():
        """Returns the basename of __file__ without a trailing 'c'"""
        filename = os.path.basename(__file__)
        if filename.endswith('.pyc'):
            filename = filename[:-1]
        return filename

    def testGet(self):
        @self.app.route('/')
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        with self.app.app_context():
            doc = self.autodoc.generate()
        self.assertTrue(len(doc) == 1)
        d = doc[0]
        self.assertIn('GET', d['methods'])
        self.assertNotIn('POST', d['methods'])
        self.assertEqual(d['rule'], '/')
        self.assertEqual(d['endpoint'], 'index')
        self.assertEqual(d['docstring'], 'Returns a hello world message')
        self.assertIsInstance(d['location']['line'], int)
        self.assertIn(self.thisFile(), d['location']['filename'])
        self.assertFalse(d['defaults'])

    def testPost(self):
        @self.app.route('/', methods=['POST'])
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 1)
            d = doc[0]
            self.assertIn('POST', d['methods'])
            self.assertNotIn('GET', d['methods'])
            self.assertEqual(d['rule'], '/')
            self.assertEqual(d['endpoint'], 'index')
            self.assertEqual(d['docstring'], 'Returns a hello world message')
            self.assertIsInstance(d['location']['line'], int)
            self.assertIn(self.thisFile(), d['location']['filename'])
            self.assertFalse(d['defaults'])

    def testParams(self):
        @self.app.route('/p1/p2', defaults={'param1': 'a', 'param2': 'b'})
        @self.app.route('/p1/<string:param1>/p2/<int:param2>')
        @self.autodoc.doc()
        def ab(param1, param2):
            return 'param1=%s param2=%s' % (param1, param2)

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 2)

            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertTrue('/p1/p2' in rules)
            self.assertTrue('/p1/<string:param1>/p2/<int:param2>' in rules)

            for d in doc:
                self.assertEqual(d['endpoint'], 'ab')
                self.assertIsNone(d['docstring'])

                if '/p1/p2' in d['rule']:
                    self.assertDictEqual(d['defaults'],
                                         {'param2': 'b', 'param1': 'a'})
                elif '/p1/<string:param1>/p2/<int:param2>' in d['rule']:
                    self.assertFalse(d['defaults'])

    def testGroup(self):
        @self.app.route('/pri')
        @self.autodoc.doc('private')
        def pri():
            return 'This is a private endpoint'

        @self.app.route('/pub')
        @self.autodoc.doc('public')
        def pub():
            return 'This is a public endpoint'

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 2)

            doc = self.autodoc.generate('all')
            self.assertTrue(len(doc) == 2)

            doc = self.autodoc.generate('private')
            self.assertTrue(len(doc) == 1)
            self.assertIn('/pri', doc[0]['rule'])

            doc = self.autodoc.generate('public')
            self.assertTrue(len(doc) == 1)
            self.assertIn('/pub', doc[0]['rule'])

    def testGroups(self):
        @self.app.route('/a')
        @self.autodoc.doc()
        def a():
            return 'Hello world, a!'

        @self.app.route('/b')
        @self.autodoc.doc(groups=['group1', 'group2'])
        def b():
            return 'Hello world, b!'

        @self.app.route('/c')
        @self.autodoc.doc('group2')
        def c():
            return 'Hello world, c!'

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 3)

            doc = self.autodoc.generate('all')
            self.assertTrue(len(doc) == 3)

            doc = self.autodoc.generate('group1')
            self.assertTrue(len(doc) == 1)
            self.assertIn('/b', doc[0]['rule'])

            doc = self.autodoc.generate('group2')
            self.assertTrue(len(doc) == 2)
            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertIn('/b', rules)
            self.assertIn('/c', rules)

            doc = self.autodoc.generate(groups=['group2'])
            self.assertTrue(len(doc) == 2)
            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertIn('/b', rules)
            self.assertIn('/c', rules)

    def testCustomParams(self):
        @self.app.route('/needsargs', methods=['GET'])
        @self.autodoc.doc('needs_getargs', getargs={
            'a': 'A Value',
            'b': 'B Value'  
            })
        def getit():
            return 'I need specific GET parameters.'

        @self.app.route('/noargs')
        @self.autodoc.doc(groups=['needs_json', 'noargs'],
            expected_type='application/json')
        def needjson():
            return 'I do not need any parameters, but am picky about types.'

        with self.app.app_context():
            doc = self.autodoc.generate('needs_getargs')
            self.assertTrue(len(doc) == 1)
            self.assertIn('getargs', doc[0])
            self.assertEqual('B Value', doc[0]['getargs']['b'])

            doc = self.autodoc.generate('noargs')
            self.assertTrue(len(doc) == 1)
            self.assertNotIn('getargs', doc[0])

            doc = self.autodoc.generate('needs_json')
            self.assertTrue(len(doc) == 1)
            self.assertIn('expected_type', doc[0])
            self.assertEqual('application/json', doc[0]['expected_type'])

    def testOverrideParams(self):
        @self.app.route('/added')
        @self.autodoc.doc('add', args=['option'])
        def original():
            return 'I make my own options.'

        @self.app.route('/modified', defaults={'option1': 1})
        @self.app.route('/modified/<int:option1>')
        @self.autodoc.doc('modify', args=['option2'], defaults=[2])
        def override_allowed(option1):
            return 'I modify my own options.'

        @self.app.route('/prohibited')
        @self.autodoc.doc('fail', rule='/not/supposed/to/be/here')
        def override_prohibited():
            return 'I make my own rules.'

        with self.app.app_context():
            doc = self.autodoc.generate('add')
            self.assertTrue(len(doc) == 1)
            self.assertIn('option', doc[0]['args'])

            doc = self.autodoc.generate('modify')
            args = [doc[i]['args'] for i in range(len(doc))]
            defaults = [doc[i]['defaults'] for i in range(len(doc))]
            self.assertNotIn(['option1'], args)
            self.assertNotIn([1], defaults)
            self.assertIn(['option2'], args)
            self.assertIn([2], defaults)

            doc = self.autodoc.generate('fail')
            self.assertTrue(len(doc) == 1)
            self.assertNotEqual('/not/supposed/to/be/here', doc[0]['rule'])
            self.assertEqual('/prohibited', doc[0]['rule'])

    def testHTML(self):
        @self.app.route('/')
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        with self.app.app_context():
            doc = self.autodoc.html()
            self.assertIn('/', doc)
            self.assertIn('Returns a hello world message', doc)

    def testHTMLWithArgs(self):
        @self.app.route('/p1/p2', defaults={'param1': 'a', 'param2': 'b'})
        @self.app.route('/p1/<string:param1>/p2/<int:param2>')
        @self.autodoc.doc()
        def ab(param1, param2):
            """Returns arguments

            This endpoint returns the value of the 2 parameters:
            - param1
            - param2
            """
            return 'param1=%s param2=%s' % (param1, param2)

        with self.app.app_context():
            doc = self.autodoc.html(title='hello')
            self.assertIn('/p1/p2', doc)
            if sys.version < '3':
                self.assertRegexpMatches(
                    doc,
                    '\/p1\/.*string:param1.*\/p2\/.*int:param2.*'
                )
            else:
                self.assertRegex(
                    doc,
                    '\/p1\/.*string:param1.*\/p2\/.*int:param2.*'
                )
            self.assertIn('Returns arguments', doc)

    def testLocation(self):
        line_no = inspect.stack()[0][2] + 2 # the doc() line
        @self.app.route('/location')
        @self.autodoc.doc()
        def location():
            return 'location'

        with self.app.app_context():
            doc = self.autodoc.generate()
            d = doc[0]
            self.assertIsInstance(d['location']['line'], int)
            self.assertEqual(d['location']['line'], line_no)
            self.assertIn(self.thisFile(), d['location']['filename'])

    def testNoLocation(self):
        @self.app.route('/location')
        @self.autodoc.doc(set_location=False)
        def location():
            return 'location'

        with self.app.app_context():
            doc = self.autodoc.generate()
            d = doc[0]
            self.assertIsNone(d['location'])

    def testRedecorate(self):
        @self.app.route('/redecorate')
        # add to "all" and "group1"
        @self.autodoc.doc('group1')
        def redecorate():
            return 'redecorate'

        # add to "group2"
        self.app.view_functions['redecorate'] = self.autodoc.doc('group2')(redecorate)

        with self.app.app_context():
            self.assertTrue(1 == len(self.autodoc.generate('all')))
            self.assertTrue(1 == len(self.autodoc.generate('group1')))
            self.assertTrue(1 == len(self.autodoc.generate('group2')))
            self.assertFalse(1 == len(self.autodoc.generate('group3')))
コード例 #11
0
from celery import Celery
import __builtin__

# Argument parser
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("-c")
args = arg_parser.parse_args()

# Config
cfg = read_config_file(args.c)

# Create App
app = Flask(__name__, static_url_path='')
app.secret_key = SECRET_KEY
app.permanent_session_lifetime = SESSION_DURATION
documentor = Autodoc(app)
app.config['MONGODB_SETTINGS'] = {
    'db': cfg["database"]["name"],
    'host': cfg["database"]["host"],
    'port': cfg["database"]["port"]
}

# Celery
app.config['CELERY_BROKER_URL'] = cfg['redis']['url']
app.config['CELERY_RESULT_BACKEND'] = cfg['redis']['url']


def make_celery(app):
    celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task
コード例 #12
0
ファイル: test_autodoc.py プロジェクト: strachg/flask-autodoc
class TestAutodoc(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.app.debug = True
        self.autodoc = Autodoc(self.app)

    @staticmethod
    def thisFile():
        """Returns the basename of __file__ without a trailing 'c'"""
        filename = os.path.basename(__file__)
        if filename.endswith('.pyc'):
            filename = filename[:-1]
        return filename

    def testGet(self):
        @self.app.route('/')
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        with self.app.app_context():
            doc = self.autodoc.generate()
        self.assertTrue(len(doc) == 1)
        d = doc[0]
        self.assertIn('GET', d['methods'])
        self.assertNotIn('POST', d['methods'])
        self.assertEqual(d['rule'], '/')
        self.assertEqual(d['endpoint'], 'index')
        self.assertEqual(d['docstring'], 'Returns a hello world message')
        self.assertIsInstance(d['location']['line'], int)
        self.assertIn(self.thisFile(), d['location']['filename'])
        self.assertFalse(d['defaults'])

    def testPost(self):
        @self.app.route('/', methods=['POST'])
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 1)
            d = doc[0]
            self.assertIn('POST', d['methods'])
            self.assertNotIn('GET', d['methods'])
            self.assertEqual(d['rule'], '/')
            self.assertEqual(d['endpoint'], 'index')
            self.assertEqual(d['docstring'], 'Returns a hello world message')
            self.assertIsInstance(d['location']['line'], int)
            self.assertIn(self.thisFile(), d['location']['filename'])
            self.assertFalse(d['defaults'])

    def testParams(self):
        @self.app.route('/p1/p2', defaults={'param1': 'a', 'param2': 'b'})
        @self.app.route('/p1/<string:param1>/p2/<int:param2>')
        @self.autodoc.doc()
        def ab(param1, param2):
            return 'param1=%s param2=%s' % (param1, param2)

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 2)

            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertTrue('/p1/p2' in rules)
            self.assertTrue('/p1/<string:param1>/p2/<int:param2>' in rules)

            for d in doc:
                self.assertEqual(d['endpoint'], 'ab')
                self.assertIsNone(d['docstring'])

                if '/p1/p2' in d['rule']:
                    self.assertDictEqual(d['defaults'], {
                        'param2': 'b',
                        'param1': 'a'
                    })
                elif '/p1/<string:param1>/p2/<int:param2>' in d['rule']:
                    self.assertFalse(d['defaults'])

    def testGroup(self):
        @self.app.route('/pri')
        @self.autodoc.doc('private')
        def pri():
            return 'This is a private endpoint'

        @self.app.route('/pub')
        @self.autodoc.doc('public')
        def pub():
            return 'This is a public endpoint'

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 2)

            doc = self.autodoc.generate('all')
            self.assertTrue(len(doc) == 2)

            doc = self.autodoc.generate('private')
            self.assertTrue(len(doc) == 1)
            self.assertIn('/pri', doc[0]['rule'])

            doc = self.autodoc.generate('public')
            self.assertTrue(len(doc) == 1)
            self.assertIn('/pub', doc[0]['rule'])

    def testGroups(self):
        @self.app.route('/a')
        @self.autodoc.doc()
        def a():
            return 'Hello world, a!'

        @self.app.route('/b')
        @self.autodoc.doc(groups=['group1', 'group2'])
        def b():
            return 'Hello world, b!'

        @self.app.route('/c')
        @self.autodoc.doc('group2')
        def c():
            return 'Hello world, c!'

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 3)

            doc = self.autodoc.generate('all')
            self.assertTrue(len(doc) == 3)

            doc = self.autodoc.generate('group1')
            self.assertTrue(len(doc) == 1)
            self.assertIn('/b', doc[0]['rule'])

            doc = self.autodoc.generate('group2')
            self.assertTrue(len(doc) == 2)
            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertIn('/b', rules)
            self.assertIn('/c', rules)

            doc = self.autodoc.generate(groups=['group2'])
            self.assertTrue(len(doc) == 2)
            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertIn('/b', rules)
            self.assertIn('/c', rules)

    def testCustomParams(self):
        @self.app.route('/needsargs', methods=['GET'])
        @self.autodoc.doc('needs_getargs',
                          getargs={
                              'a': 'A Value',
                              'b': 'B Value'
                          })
        def getit():
            return 'I need specific GET parameters.'

        @self.app.route('/noargs')
        @self.autodoc.doc(groups=['needs_json', 'noargs'],
                          expected_type='application/json')
        def needjson():
            return 'I do not need any parameters, but am picky about types.'

        with self.app.app_context():
            doc = self.autodoc.generate('needs_getargs')
            self.assertTrue(len(doc) == 1)
            self.assertIn('getargs', doc[0])
            self.assertEqual('B Value', doc[0]['getargs']['b'])

            doc = self.autodoc.generate('noargs')
            self.assertTrue(len(doc) == 1)
            self.assertNotIn('getargs', doc[0])

            doc = self.autodoc.generate('needs_json')
            self.assertTrue(len(doc) == 1)
            self.assertIn('expected_type', doc[0])
            self.assertEqual('application/json', doc[0]['expected_type'])

    def testOverrideParams(self):
        @self.app.route('/added')
        @self.autodoc.doc('add', args=['option'])
        def original():
            return 'I make my own options.'

        @self.app.route('/modified', defaults={'option1': 1})
        @self.app.route('/modified/<int:option1>')
        @self.autodoc.doc('modify', args=['option2'], defaults=[2])
        def override_allowed(option1):
            return 'I modify my own options.'

        @self.app.route('/prohibited')
        @self.autodoc.doc('fail', rule='/not/supposed/to/be/here')
        def override_prohibited():
            return 'I make my own rules.'

        with self.app.app_context():
            doc = self.autodoc.generate('add')
            self.assertTrue(len(doc) == 1)
            self.assertIn('option', doc[0]['args'])

            doc = self.autodoc.generate('modify')
            args = [doc[i]['args'] for i in range(len(doc))]
            defaults = [doc[i]['defaults'] for i in range(len(doc))]
            self.assertNotIn(['option1'], args)
            self.assertNotIn([1], defaults)
            self.assertIn(['option2'], args)
            self.assertIn([2], defaults)

            doc = self.autodoc.generate('fail')
            self.assertTrue(len(doc) == 1)
            self.assertNotEqual('/not/supposed/to/be/here', doc[0]['rule'])
            self.assertEqual('/prohibited', doc[0]['rule'])

    def testHTML(self):
        @self.app.route('/')
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        with self.app.app_context():
            doc = self.autodoc.html()
            self.assertIn('/', doc)
            self.assertIn('Returns a hello world message', doc)

    def testHTMLWithArgs(self):
        @self.app.route('/p1/p2', defaults={'param1': 'a', 'param2': 'b'})
        @self.app.route('/p1/<string:param1>/p2/<int:param2>')
        @self.autodoc.doc()
        def ab(param1, param2):
            """Returns arguments

            This endpoint returns the value of the 2 parameters:
            - param1
            - param2
            """
            return 'param1=%s param2=%s' % (param1, param2)

        with self.app.app_context():
            doc = self.autodoc.html(title='hello')
            self.assertIn('/p1/p2', doc)
            if sys.version < '3':
                self.assertRegexpMatches(
                    doc, '\/p1\/.*string:param1.*\/p2\/.*int:param2.*')
            else:
                self.assertRegex(
                    doc, '\/p1\/.*string:param1.*\/p2\/.*int:param2.*')
            self.assertIn('Returns arguments', doc)

    def testLocation(self):
        line_no = inspect.stack()[0][2] + 2  # the doc() line

        @self.app.route('/location')
        @self.autodoc.doc()
        def location():
            return 'location'

        with self.app.app_context():
            doc = self.autodoc.generate()
            d = doc[0]
            self.assertIsInstance(d['location']['line'], int)
            self.assertEqual(d['location']['line'], line_no)
            self.assertIn(self.thisFile(), d['location']['filename'])

    def testNoLocation(self):
        @self.app.route('/location')
        @self.autodoc.doc(set_location=False)
        def location():
            return 'location'

        with self.app.app_context():
            doc = self.autodoc.generate()
            d = doc[0]
            self.assertIsNone(d['location'])

    def testRedecorate(self):
        @self.app.route('/redecorate')
        # add to "all" and "group1"
        @self.autodoc.doc('group1')
        def redecorate():
            return 'redecorate'

        # add to "group2"
        self.app.view_functions['redecorate'] = self.autodoc.doc('group2')(
            redecorate)

        with self.app.app_context():
            self.assertTrue(1 == len(self.autodoc.generate('all')))
            self.assertTrue(1 == len(self.autodoc.generate('group1')))
            self.assertTrue(1 == len(self.autodoc.generate('group2')))
            self.assertFalse(1 == len(self.autodoc.generate('group3')))
コード例 #13
0
ファイル: app.py プロジェクト: LoveMyDaughter/ecomap
from flask import Flask
from flask.ext.cache import Cache
from flask.ext.session import Session
from flask.ext.autodoc import Autodoc
from flask.ext.triangle import Triangle
from werkzeug.contrib.cache import MemcachedCache

from ecomap.config import Config

_CONFIG = Config().get_config()

TEMPLATE_FOLDER = os.path.join(os.environ['PRODROOT'], 'www/templates/')
app = Flask(__name__, template_folder=TEMPLATE_FOLDER)
Triangle(app)
auto = Autodoc(app)

logging.config.fileConfig(os.path.join(os.environ['CONFROOT'], '_log.conf'))
logger = logging.getLogger('flask_app')
app.config['SECRET_KEY'] = 'a7c268ab01141868811c070274413ea3c588733241659fcb'
app.config["REMEMBER_COOKIE_DURATION"] = timedelta(days=14)  # user time lib
app.config['SECRET_KEY'] = _CONFIG['ecomap.secret_key']
app.config['CACHE_TYPE'] = 'memcached'
app.config['SESSION_TYPE'] = 'memcached'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=14)
app.config['SESSION_MEMCACHED'] = MemcachedCache(
    _CONFIG['ecomap.memcached_servers'])
app.config['CACHE_MEMCACHED_SERVERS'] = _CONFIG['ecomap.memcached_servers']
app.config['OAUTH_CREDENTIALS'] = {
    'facebook': {
        'id': _CONFIG['oauth.facebook_id'],
コード例 #14
0
class TestAutodoc(unittest.TestCase):

    def setUp(self):
        self.app = Flask(__name__)
        self.app.debug = True
        self.autodoc = Autodoc(self.app)

    def testGet(self):
        @self.app.route('/')
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        with self.app.app_context():
            doc = self.autodoc.generate()
        self.assertTrue(len(doc) == 1)
        d = doc[0]
        self.assertIn('GET', d['methods'])
        self.assertNotIn('POST', d['methods'])
        self.assertEqual(d['rule'], '/')
        self.assertEqual(d['endpoint'], 'index')
        self.assertEqual(d['docstring'], 'Returns a hello world message')
        self.assertFalse(d['defaults'])

    def testPost(self):
        @self.app.route('/', methods=['POST'])
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 1)
            d = doc[0]
            self.assertIn('POST', d['methods'])
            self.assertNotIn('GET', d['methods'])
            self.assertEqual(d['rule'], '/')
            self.assertEqual(d['endpoint'], 'index')
            self.assertEqual(d['docstring'], 'Returns a hello world message')
            self.assertFalse(d['defaults'])

    def testParams(self):
        @self.app.route('/p1/p2', defaults={'param1': 'a', 'param2': 'b'})
        @self.app.route('/p1/<string:param1>/p2/<int:param2>')
        @self.autodoc.doc()
        def ab(param1, param2):
            return 'param1=%s param2=%s' % (param1, param2)

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 2)

            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertTrue('/p1/p2' in rules)
            self.assertTrue('/p1/<string:param1>/p2/<int:param2>' in rules)

            for d in doc:
                self.assertEqual(d['endpoint'], 'ab')
                self.assertIsNone(d['docstring'])

                if '/p1/p2' in d['rule']:
                    self.assertDictEqual(d['defaults'],
                                         {'param2': 'b', 'param1': 'a'})
                elif '/p1/<string:param1>/p2/<int:param2>' in d['rule']:
                    self.assertFalse(d['defaults'])

    def testGroup(self):
        @self.app.route('/pri')
        @self.autodoc.doc('private')
        def pri():
            return 'This is a private endpoint'

        @self.app.route('/pub')
        @self.autodoc.doc('public')
        def pub():
            return 'This is a public endpoint'

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 2)

            doc = self.autodoc.generate('all')
            self.assertTrue(len(doc) == 2)

            doc = self.autodoc.generate('private')
            self.assertTrue(len(doc) == 1)
            self.assertIn('/pri', doc[0]['rule'])

            doc = self.autodoc.generate('public')
            self.assertTrue(len(doc) == 1)
            self.assertIn('/pub', doc[0]['rule'])

    def testGroups(self):

        @self.app.route('/a')
        @self.autodoc.doc()
        def a():
            return 'Hello world, a!'

        @self.app.route('/b')
        @self.autodoc.doc(groups=['group1', 'group2'])
        def b():
            return 'Hello world, b!'

        @self.app.route('/c')
        @self.autodoc.doc('group2')
        def c():
            return 'Hello world, c!'

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 3)

            doc = self.autodoc.generate('all')
            self.assertTrue(len(doc) == 3)

            doc = self.autodoc.generate('group1')
            self.assertTrue(len(doc) == 1)
            self.assertIn('/b', doc[0]['rule'])

            doc = self.autodoc.generate('group2')
            self.assertTrue(len(doc) == 2)
            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertIn('/b', rules)
            self.assertIn('/c', rules)

            doc = self.autodoc.generate(groups=['group2'])
            self.assertTrue(len(doc) == 2)
            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertIn('/b', rules)
            self.assertIn('/c', rules)

    def testHTML(self):
        @self.app.route('/')
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        with self.app.app_context():
            doc = self.autodoc.html()
            self.assertIn('/', doc)
            self.assertIn('Returns a hello world message', doc)

    def testHTMLWithArgs(self):
        @self.app.route('/p1/p2', defaults={'param1': 'a', 'param2': 'b'})
        @self.app.route('/p1/<string:param1>/p2/<int:param2>')
        @self.autodoc.doc()
        def ab(param1, param2):
            """Returns arguments

            This endpoint returns the value of the 2 parameters:
            - param1
            - param2
            """
            return 'param1=%s param2=%s' % (param1, param2)

        with self.app.app_context():
            doc = self.autodoc.html(title='hello')
            self.assertIn('/p1/p2', doc)
            if sys.version < '3':
                self.assertRegexpMatches(
                    doc,
                    '\/p1\/.*string:param1.*\/p2\/.*int:param2.*'
                )
            else:
                self.assertRegex(
                    doc,
                    '\/p1\/.*string:param1.*\/p2\/.*int:param2.*'
                )
            self.assertIn('Returns arguments', doc)
コード例 #15
0
def create_app():
    Autodoc(app)
    # cal = Calendar()
    babel.init_app(app)

    app.register_blueprint(babel_routes)
    app.register_blueprint(api_v1_routes)
    app.register_blueprint(sitemap_routes)
    Migrate(app, db)

    app.config.from_object(environ.get('APP_CONFIG',
                                       'config.ProductionConfig'))
    db.init_app(app)
    manager = Manager(app)
    manager.add_command('db', MigrateCommand)

    if app.config['CACHING']:
        cache.init_app(app, config={'CACHE_TYPE': 'simple'})
    else:
        cache.init_app(app, config={'CACHE_TYPE': 'null'})

    CORS(app)
    stripe.api_key = 'SomeStripeKey'
    app.secret_key = 'super secret key'
    app.json_encoder = MiniJSONEncoder
    app.config['BABEL_DEFAULT_LOCALE'] = 'en'
    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
    app.config['UPLOADS_FOLDER'] = os.path.realpath('.') + '/static/'
    app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'
    app.config['STATIC_URL'] = '/static/'
    app.config['STATIC_ROOT'] = 'staticfiles'
    app.config['STATICFILES_DIRS'] = (os.path.join(BASE_DIR, 'static'), )
    app.config['SQLALCHEMY_RECORD_QUERIES'] = True

    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    app.logger.setLevel(logging.WARNING)
    app.jinja_env.add_extension('jinja2.ext.do')
    app.jinja_env.add_extension('jinja2.ext.loopcontrols')
    app.jinja_env.undefined = SilentUndefined
    app.jinja_env.filters['operation_name'] = operation_name

    # set up jwt
    app.config['JWT_AUTH_USERNAME_KEY'] = 'email'
    app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=24 * 60 * 60)
    app.config['JWT_AUTH_URL_RULE'] = None
    jwt = JWT(app, jwt_authenticate, jwt_identity)

    # setup celery
    app.config['CELERY_BROKER_URL'] = environ.get('REDIS_URL',
                                                  'redis://localhost:6379/0')
    app.config['CELERY_RESULT_BACKEND'] = app.config['CELERY_BROKER_URL']

    HTMLMIN(app)
    admin_view = AdminView("Open Event")
    admin_view.init(app)
    admin_view.init_login(app)

    if app.config['TESTING']:
        # Profiling
        app.config['PROFILE'] = True
        app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])

    # API version 2
    with app.app_context():
        from app.api import api_v2
        app.register_blueprint(api_v2)

    sa.orm.configure_mappers()

    return app, manager, db, jwt
コード例 #16
0
ファイル: test_autodoc.py プロジェクト: jwg4/flask-autodoc
class TestAutodoc(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.app.debug = True
        self.autodoc = Autodoc(self.app)

    def testGet(self):
        @self.app.route("/")
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return "Hello World!"

        with self.app.app_context():
            doc = self.autodoc.generate()
        self.assertTrue(len(doc) == 1)
        d = doc[0]
        self.assertIn("GET", d["methods"])
        self.assertNotIn("POST", d["methods"])
        self.assertEqual(d["rule"], "/")
        self.assertEqual(d["endpoint"], "index")
        self.assertEqual(d["docstring"], "Returns a hello world message")
        self.assertIsInstance(d["location"]["line"], int)
        self.assertIn(__file__, d["location"]["filename"])
        self.assertFalse(d["defaults"])

    def testPost(self):
        @self.app.route("/", methods=["POST"])
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return "Hello World!"

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 1)
            d = doc[0]
            self.assertIn("POST", d["methods"])
            self.assertNotIn("GET", d["methods"])
            self.assertEqual(d["rule"], "/")
            self.assertEqual(d["endpoint"], "index")
            self.assertEqual(d["docstring"], "Returns a hello world message")
            self.assertIsInstance(d["location"]["line"], int)
            self.assertIn(__file__, d["location"]["filename"])
            self.assertFalse(d["defaults"])

    def testParams(self):
        @self.app.route("/p1/p2", defaults={"param1": "a", "param2": "b"})
        @self.app.route("/p1/<string:param1>/p2/<int:param2>")
        @self.autodoc.doc()
        def ab(param1, param2):
            return "param1=%s param2=%s" % (param1, param2)

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 2)

            rules = [doc[i]["rule"] for i in range(len(doc))]
            self.assertTrue("/p1/p2" in rules)
            self.assertTrue("/p1/<string:param1>/p2/<int:param2>" in rules)

            for d in doc:
                self.assertEqual(d["endpoint"], "ab")
                self.assertIsNone(d["docstring"])

                if "/p1/p2" in d["rule"]:
                    self.assertDictEqual(d["defaults"], {"param2": "b", "param1": "a"})
                elif "/p1/<string:param1>/p2/<int:param2>" in d["rule"]:
                    self.assertFalse(d["defaults"])

    def testGroup(self):
        @self.app.route("/pri")
        @self.autodoc.doc("private")
        def pri():
            return "This is a private endpoint"

        @self.app.route("/pub")
        @self.autodoc.doc("public")
        def pub():
            return "This is a public endpoint"

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 2)

            doc = self.autodoc.generate("all")
            self.assertTrue(len(doc) == 2)

            doc = self.autodoc.generate("private")
            self.assertTrue(len(doc) == 1)
            self.assertIn("/pri", doc[0]["rule"])

            doc = self.autodoc.generate("public")
            self.assertTrue(len(doc) == 1)
            self.assertIn("/pub", doc[0]["rule"])

    def testGroups(self):
        @self.app.route("/a")
        @self.autodoc.doc()
        def a():
            return "Hello world, a!"

        @self.app.route("/b")
        @self.autodoc.doc(groups=["group1", "group2"])
        def b():
            return "Hello world, b!"

        @self.app.route("/c")
        @self.autodoc.doc("group2")
        def c():
            return "Hello world, c!"

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 3)

            doc = self.autodoc.generate("all")
            self.assertTrue(len(doc) == 3)

            doc = self.autodoc.generate("group1")
            self.assertTrue(len(doc) == 1)
            self.assertIn("/b", doc[0]["rule"])

            doc = self.autodoc.generate("group2")
            self.assertTrue(len(doc) == 2)
            rules = [doc[i]["rule"] for i in range(len(doc))]
            self.assertIn("/b", rules)
            self.assertIn("/c", rules)

            doc = self.autodoc.generate(groups=["group2"])
            self.assertTrue(len(doc) == 2)
            rules = [doc[i]["rule"] for i in range(len(doc))]
            self.assertIn("/b", rules)
            self.assertIn("/c", rules)

    def testHTML(self):
        @self.app.route("/")
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return "Hello World!"

        with self.app.app_context():
            doc = self.autodoc.html()
            self.assertIn("/", doc)
            self.assertIn("Returns a hello world message", doc)

    def testHTMLWithArgs(self):
        @self.app.route("/p1/p2", defaults={"param1": "a", "param2": "b"})
        @self.app.route("/p1/<string:param1>/p2/<int:param2>")
        @self.autodoc.doc()
        def ab(param1, param2):
            """Returns arguments

            This endpoint returns the value of the 2 parameters:
            - param1
            - param2
            """
            return "param1=%s param2=%s" % (param1, param2)

        with self.app.app_context():
            doc = self.autodoc.html(title="hello")
            self.assertIn("/p1/p2", doc)
            if sys.version < "3":
                self.assertRegexpMatches(doc, "\/p1\/.*string:param1.*\/p2\/.*int:param2.*")
            else:
                self.assertRegex(doc, "\/p1\/.*string:param1.*\/p2\/.*int:param2.*")
            self.assertIn("Returns arguments", doc)
コード例 #17
0
class TestAutodoc(unittest.TestCase):

    def setUp(self):
        self.app = Flask(__name__)
        self.app.debug = True
        self.autodoc = Autodoc(self.app)

    def testGet(self):
        @self.app.route("/")
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return "Hello World!"

        with self.app.app_context():
            doc = self.autodoc.generate()
        self.assertTrue(len(doc) == 1)
        d = doc[0]
        self.assertIn('GET', d['methods'])
        self.assertNotIn('POST', d['methods'])
        self.assertEqual(d['rule'], '/')
        self.assertEqual(d['endpoint'], 'index')
        self.assertEqual(d['docstring'], "Returns a hello world message")
        self.assertFalse(d['defaults'])

    def testPost(self):
        @self.app.route("/", methods=['POST'])
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return "Hello World!"

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 1)
            d = doc[0]
            self.assertIn('POST', d['methods'])
            self.assertNotIn('GET', d['methods'])
            self.assertEqual(d['rule'], '/')
            self.assertEqual(d['endpoint'], 'index')
            self.assertEqual(d['docstring'], "Returns a hello world message")
            self.assertFalse(d['defaults'])

    def testParams(self):
        @self.app.route("/p1/p2", defaults={'param1': 'a', 'param2': 'b'})
        @self.app.route("/p1/<string:param1>/p2/<int:param2>")
        @self.autodoc.doc()
        def ab(param1, param2):
            return "param1=%s param2=%2" % (param1, param2)

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 2)

            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertTrue("/p1/p2" in rules)
            self.assertTrue("/p1/<string:param1>/p2/<int:param2>" in rules)

            for d in doc:
                self.assertEqual(d['endpoint'], 'ab')
                self.assertIsNone(d['docstring'])

                if "/p1/p2" in d['rule']:
                    self.assertDictEqual(d['defaults'], {'param2': 'b', 'param1': 'a'})
                elif "/p1/<string:param1>/p2/<int:param2>" in d['rule']:
                    self.assertFalse(d['defaults'])

    def testGroup(self):
        @self.app.route("/pri")
        @self.autodoc.doc("private")
        def pri():
            return "This is a private endpoint"

        @self.app.route("/pub")
        @self.autodoc.doc("public")
        def pub():
            return "This is a public endpoint"

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 2)

            doc = self.autodoc.generate("all")
            self.assertTrue(len(doc) == 2)

            doc = self.autodoc.generate("private")
            self.assertTrue(len(doc) == 1)
            self.assertIn("/pri", doc[0]['rule'])

            doc = self.autodoc.generate("public")
            self.assertTrue(len(doc) == 1)
            self.assertIn("/pub", doc[0]['rule'])

    def testGroups(self):

        @self.app.route("/a")
        @self.autodoc.doc()
        def a():
            return "Hello world, a!"

        @self.app.route("/b")
        @self.autodoc.doc(groups=["group1", "group2"])
        def b():
            return "Hello world, b!"

        @self.app.route("/c")
        @self.autodoc.doc("group2")
        def c():
            return "Hello world, c!"

        with self.app.app_context():
            doc = self.autodoc.generate()
            self.assertTrue(len(doc) == 3)

            doc = self.autodoc.generate("all")
            self.assertTrue(len(doc) == 3)

            doc = self.autodoc.generate("group1")
            self.assertTrue(len(doc) == 1)
            self.assertIn("/b", doc[0]['rule'])

            doc = self.autodoc.generate("group2")
            self.assertTrue(len(doc) == 2)
            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertIn("/b", rules)
            self.assertIn("/c", rules)

            doc = self.autodoc.generate(groups=["group2"])
            self.assertTrue(len(doc) == 2)
            rules = [doc[i]['rule'] for i in range(len(doc))]
            self.assertIn("/b", rules)
            self.assertIn("/c", rules)

    def testHTML(self):
        @self.app.route("/")
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return "Hello World!"

        with self.app.app_context():
            doc = self.autodoc.html()
            self.assertIn("/", doc)
            self.assertIn("Returns a hello world message", doc)

    def testHTMLWithArgs(self):
        @self.app.route("/p1/p2", defaults={'param1': 'a', 'param2': 'b'})
        @self.app.route("/p1/<string:param1>/p2/<int:param2>")
        @self.autodoc.doc()
        def ab(param1, param2):
            """Returns arguments

            This endpoint returns the value of the 2 parameters:
            - param1
            - param2
            """
            return "param1=%s param2=%2" % (param1, param2)

        with self.app.app_context():
            doc = self.autodoc.html(title="hello")
            self.assertIn("/p1/p2", doc)
            self.assertRegexpMatches(doc, "\/p1\/.*string:param1.*\/p2\/.*int:param2.*")
            self.assertIn("Returns arguments", doc)
コード例 #18
0
### Create Flask, Scheduler and SocketIO objects

app = flask.Flask(__name__)
app.config['DEBUG'] = True
# Disable CSRF checking in WTForms
app.config['WTF_CSRF_ENABLED'] = False
# This is still necessary for SocketIO
app.config['SECRET_KEY'] = config_value('secret_key')
app.url_map.redirect_defaults = False
socketio = SocketIO(app)
scheduler = digits.scheduler.Scheduler(config_value('gpu_list'))

# Set up flask API documentation, if installed
try:
    from flask.ext.autodoc import Autodoc
    _doc = Autodoc(app)
    autodoc = _doc.doc  # decorator
except ImportError:

    def autodoc(*args, **kwargs):
        def _doc(f):
            # noop decorator
            return f

        return _doc


### Register filters and views

app.jinja_env.globals['server_name'] = config_value('server_name')
app.jinja_env.globals['server_version'] = digits.__version__
コード例 #19
0
ファイル: apiair.py プロジェクト: LABintheAIR/apiair
import random
import pandas
import tinydb
from version import version
import colorutils
from flask import Flask, jsonify, request
from flask.ext.autodoc import Autodoc
from simplecrypt import decrypt
from geopy.distance import vincenty

# Dossier des données
datadir = os.environ.get('OPENSHIFT_DATA_DIR', '.')

# Application Flask
app = Flask('apiair')
autodoc = Autodoc(app)  # Autodoc extension

# Stockage des données
fndb = os.path.join(datadir, '{region}_iqa.json')  # iqa, last hour
fndat = os.path.join(datadir, '{region}_conc.dat')  # conc, last two days

# Clé via variable d'environnement
key = os.environ['APIAIR_KEY']


def strip_with_indent(s):
    """Remove extra space in code.

    :param s: string.
    :return: string.
    """