Beispiel #1
0
def setup_api(auth):
    user_auth = UserAuthentication(auth)
    api = RestAPI(app, default_auth=user_auth)
    api.register(Note)
    api.register(Author)
    api.setup()
    return api
Beispiel #2
0
class DataStore():
    def __init__(self):
        # Initialize flask
        self.flask = Flask('data_store')
        self.api = RestAPI(self.flask)

    def register(self, model):
        self.api.register(model)
        # Configure the URLs
        self.api.setup()
Beispiel #3
0
def initialize():
    global db, api

    db = Database(app)

    # Setup models
    import models
    models.setup()

    # Register REST api
    api = RestAPI(app)
    api.register(models.Flow)
    api.setup()
Beispiel #4
0
class InitAPI2(InitBaseExtension):

    name = 'api2'

    def init_app(self, app):  # Инициализируем RestAPI от peewee
        self.extension = RestAPI(app.web_app)
        self.extension.default_auth = Authentication(protected_methods=[])

    def configurate_extension(self):

        from models import get_models

        for m in get_models():
            self.extension.register(m)

        self.extension.setup()
Beispiel #5
0
        super(AuthorizeEveryone, self).__init__()

    def authorize(self):
        """
        Like I said, authorize everyone.
        """
        return True

class QuizResource(RestResource):
    paginate_by = False

authorize_everyone = AuthorizeEveryone()

api = RestAPI(app, default_auth=authorize_everyone, prefix="/%s/api" % app_config.PROJECT_SLUG)

api.register(models.Quiz, QuizResource, allowed_methods=['GET', 'POST', 'PUT', 'DELETE'])
api.register(models.Question, allowed_methods=['GET', 'POST', 'PUT', 'DELETE'])
api.register(models.Choice, allowed_methods=['GET', 'POST', 'PUT', 'DELETE'])
api.register(models.Photo, allowed_methods=['GET', 'POST', 'PUT', 'DELETE'])
api.register(models.Audio, allowed_methods=['GET', 'POST', 'PUT', 'DELETE'])

api.setup()

@app.route('/%s/' % app_config.PROJECT_SLUG)
def index():
    """
    Render the admin index.
    """
    context = make_context()

    return render_template('index.html', **context)
Beispiel #6
0
from implemented_models import MODELS_CLASS
from decimal import Decimal

user_auth = UserAuthentication(auth, protected_methods=['GET', 'POST', 'PUT',
                                                        'DELETE'])
api = RestAPI(app, default_auth=user_auth)


class ApiResource(RestResource):
    def check_post(self, obj=None):
        return False

    def check_put(self, obj):
        return False

    def check_delete(self, obj):
        return False

    def prepare_data(self, obj, data):
        for field in data:
            if isinstance(data[field], Decimal):
                data[field] = str(data[field])
        return data

for mod_class in list(MODELS_CLASS.keys()):
    api.register(MODELS_CLASS[mod_class], ApiResource)

api.register(SyncLog, ApiResource)

api.setup()
Beispiel #7
0
from flask_peewee.rest import UserAuthentication, RestAPI, RestResource
from app import app
from auth import auth
from models import User

user_auth = UserAuthentication(auth)

api = RestAPI(app, default_auth=user_auth)


class UserResource(RestResource):
    exclude = (
        'password',
        'email',
    )


api.register(User, UserResource, auth=user_auth)
Beispiel #8
0
from peewee import *
from flask import Flask
from model.model import Book ,database
from flask_peewee.rest import RestAPI, UserAuthentication
from flask_peewee.auth import Auth

app = Flask(__name__)
app.config.from_object(__name__)


api = RestAPI(app)

api.register(Book)

# auth = Auth(app, database)
# user_auth = UserAuthentication(auth)
# api = RestAPI(app, default_auth=user_auth)

api.setup()


if __name__ == '__main__':
    app.run(debug=True)

Beispiel #9
0
from flask_limiter.util import get_remote_address

from helpers import song_join_to_json
from models import Song, Artist, Comment, Album, Playlist, Tag
from no_auth import NoAuth

user_auth = NoAuth()

models_to_register = [Song, Tag, Comment, Artist, Album, Playlist]

app = Flask(__name__)
api = RestAPI(app, default_auth=user_auth)

# register our models so they are exposed via /api/<model>/
for model_to_register in models_to_register:
    api.register(model_to_register)

# configure the urls
api.setup()

rest_app = api.app

# configure limiter in order to prevent abuse
limiter = Limiter(
    rest_app,
    key_func=get_remote_address,
    default_limits=["50 per second"]
)


@rest_app.route('/')
Beispiel #10
0
# instantiate our api wrapper and tell it to use HTTP basic auth using
# the same credentials as our auth system.  If you prefer this could
# instead be a key-based auth, or god forbid some open auth protocol.
api = RestAPI(app, default_auth=user_auth)


class UserResource(RestResource):
    exclude = (
        'password',
        'email',
    )


class Loc(RestResource):
    # exclude = ('json', 'revgeo', )
    fields = (
        'tst',
        'lat',
        'lon',
        'username',
        'device',
    )
    paginate_by = 0


# Register our models so they are exposed via /api/<model>/

#api.register(User, UserResource, auth=admin_auth)
api.register(User, UserResource)
api.register(Location, Loc)
Beispiel #11
0
from flask_peewee.rest import RestAPI, RestResource

from app import app
from customer import Customer
from product import Product

api = RestAPI(app)

api.register(Customer)
api.register(Product)

api.setup()
Beispiel #12
0
        'password',
        'email',
    )

    def get_query(self):
        return User.filter(active=True)


# rest api stuff
user_auth = UserAuthentication(auth)
admin_auth = AdminAuthentication(auth)
api_key_auth = APIKeyAuthentication(APIKey, ['GET', 'POST', 'PUT', 'DELETE'])

api = RestAPI(app, default_auth=user_auth)

api.register(Message, RestrictOwnerResource)
api.register(User, UserResource, auth=admin_auth)
api.register(Note)
api.register(TestModel, auth=api_key_auth)


# views
@app.route('/')
def homepage():
    return Response()


@app.route('/private/')
@auth.login_required
def private_timeline():
    return Response()
Beispiel #13
0
    #    return self.paginated_object_list(notes)

    def search(self):
        query = request.args.get('query')
        notes = Note.search(request.args.get('query') or '')
        notes = self.process_query(notes)  # Apply any filters, etc.
        return self.paginated_object_list(notes)

    def note_details(self, pk):
        note = get_object_or_404(self.get_query(), self.pk == pk)
        return self.response({
            'content':
            note.unparse_content(),
            'reminder': (note.reminder.strftime('%Y-%m-%dT%H:%M')
                         if note.reminder else None),
        })

    def get_query(self):
        return Note.public()

    def prepare_data(self, obj, data):
        data['rendered'] = render_template('note.html', note=obj)
        return data


class TaskResource(RestResource):
    paginate_by = 50


api.register(Note, NoteResource)
api.register(Task, TaskResource)
Beispiel #14
0
def setup_api(auth):
    user_auth = UserAuthentication(auth)
    api = RestAPI(app, default_auth=user_auth)
    api.register(User, UserResource)
    api.setup()
    return api
Beispiel #15
0
# create a special resource for users that excludes email and password
class UserResource(RestResource):
    exclude = ('password', 'email',)


# class LogrefillResource(RestResource):

#     def prepare_data(self, obj, data):
#         data["credit"] = str(data["credit"])
#         return data


# instantiate the user auth
user_auth = UserAuthentication(auth, protected_methods=['GET', 'POST', 'PUT', 'DELETE'])


# create a RestAPI container
api = RestAPI(app, default_auth=user_auth)
# register the models
api.register(Card, CardResource, auth=user_auth)
api.register(CardGroup, auth=user_auth)
api.register(Callerid, auth=user_auth)
api.register(Logrefill, auth=user_auth)
api.register(Logpayment, auth=user_auth)
api.register(Call, auth=user_auth)
api.register(Country, auth=user_auth)
api.register(Charge, auth=user_auth)
# api.register(Did, auth=user_auth)
# api.register(DidDestination, auth=user_auth)
api.register(auth.User, UserResource, auth=user_auth)
Beispiel #16
0
from flask_peewee.rest import RestAPI, UserAuthentication

from app import app
from auth import auth
from models import Note

user_auth = UserAuthentication(auth)
api = RestAPI(app, default_auth=user_auth)
api.register(Note)
api.setup()
Beispiel #17
0
from flask import Flask
from flask_peewee.rest import RestAPI
from db import Person

app = Flask(__name__)
app.config.from_object(__name__)

# create a RestAPI container
api = RestAPI(app)

# register the Note model
api.register(Person)

api.setup()

if __name__ == '__main__':
    app.run()
Beispiel #18
0
'''
Modulo gestione chiamate Restful
Es.: http://localhost:8080/api/relay/
'''
from app import app
from auth import auth
from flask_peewee.rest import RestAPI, RestResource, UserAuthentication, \
    AdminAuthentication
from models import User, Relay


class UserResource(RestResource):
    '''
    Gestione risorse User
    Consente di configurare i campi esportati nel json
    '''
    exclude = ('password', 'email',)

"Configura Authenticator per User e Admin"
user_auth = UserAuthentication(auth)
admin_auth = AdminAuthentication(auth)

"Crea oggetto API per la gestione delle chiamate Restful"
api = RestAPI(app, default_auth=user_auth)

"Registra Modelli"
api.register(User, UserResource, auth=admin_auth)
api.register(Relay)
Beispiel #19
0
from flask import Flask
from flask_peewee.rest import RestAPI

import models

app = Flask(__name__)

# instantiate our api wrapper
api = RestAPI(app)

# register our models so they are exposed via /api/<model>/
api.register(models.Article)

# configure the urls
api.setup()

if __name__ == '__main__':
    app.run(debug=True)

Beispiel #20
0
	user = ForeignKeyField(auth.User, related_name='gifts')
	item = ForeignKeyField(Item, related_name='parts')

# admin part
admin = Admin(app, auth)

admin.register(WishList)
admin.register(Item)
admin.register(Part)


# api part
user_auth = UserAuthentication(auth)
api = RestAPI(app, default_auth=user_auth)

api.register(WishList)
api.register(Item, ItemResource)
api.register(Part)

# setup
admin.setup()
api.setup()

@app.route('/') 
def index():
	return render_template('index.html')
	
if __name__ == '__main__':	 
	auth.User.create_table(fail_silently=True)
	WishList.create_table(fail_silently=True)
	Item.create_table(fail_silently=True)
Beispiel #21
0
demo.set_password("sonata")
demo.save()

admin = Admin(app, auth)

admin.register(User)
admin.register(Serie)
admin.register(Fansub)
admin.register(ScrapParam)
admin.register(ScrapParamTemplate)
admin.register(Notification)

admin.setup()

# register our models so they are exposed via /api/<model>/
api.register(User)
api.register(Serie)
api.register(Fansub)
api.register(ScrapParam)
api.register(Notification, NotificationResource)

# configure the urls
api.setup()

# HTTP error handling
@app.errorhandler(404)
def not_found(error):
    return "404: Not Found.", 404


@app.route("/")
Beispiel #22
0
        """
        return True


class QuizResource(RestResource):
    paginate_by = False


authorize_everyone = AuthorizeEveryone()

api = RestAPI(app,
              default_auth=authorize_everyone,
              prefix="/%s/api" % app_config.PROJECT_SLUG)

api.register(models.Quiz,
             QuizResource,
             allowed_methods=['GET', 'POST', 'PUT', 'DELETE'])
api.register(models.Question, allowed_methods=['GET', 'POST', 'PUT', 'DELETE'])
api.register(models.Choice, allowed_methods=['GET', 'POST', 'PUT', 'DELETE'])
api.register(models.Photo, allowed_methods=['GET', 'POST', 'PUT', 'DELETE'])
api.register(models.Audio, allowed_methods=['GET', 'POST', 'PUT', 'DELETE'])

api.setup()


@app.route('/%s/' % app_config.PROJECT_SLUG)
def index():
    """
    Render the admin index.
    """
    context = make_context()
Beispiel #23
0
from flask import render_template
from flask_peewee.rest import Authentication
from flask_peewee.rest import RestAPI
from flask_peewee.rest import RestResource

from app import app
from models import Note
from models import Task


# Allow GET and POST requests without requiring authentication.
auth = Authentication(protected_methods=['PUT', 'DELETE'])
api = RestAPI(app, default_auth=auth)

class NoteResource(RestResource):
    fields = ('id', 'content', 'timestamp', 'status')
    paginate_by = 30

    def get_query(self):
        return Note.public()

    def prepare_data(self, obj, data):
        data['rendered'] = render_template('note.html', note=obj)
        return data

class TaskResource(RestResource):
    paginate_by = 50

api.register(Note, NoteResource)
api.register(Task, TaskResource)
Beispiel #24
0
        modules = module.select().where(
            module.module_code == mod
        )  # select module data from module table in db using module_code posted by user
        authorized = False  # initialise authorized variable as False

        for item in modules:
            instructor = str(
                item.instructor)  # select instructor associated with item
            if instructor == user:
                authorized = True

        return authorized


# instantiate UserAuthentication
user_auth = UserAuthentication(auth)

# instantiate admin-only auth
admin_auth = AdminAuthentication(auth)

# instantiate our api wrapper, specifying user_auth as the default
api = RestAPI(app, default_auth=user_auth)

# register models so they are exposed via /api/<model>/
api.register(room, auth=admin_auth, allowed_methods=['GET'])
api.register(survey, SurveyResource, allowed_methods=['GET', 'POST'])
api.register(wifi_log, auth=admin_auth, allowed_methods=['GET'])
api.register(timetable, auth=admin_auth, allowed_methods=['GET'])
api.register(module, auth=admin_auth, allowed_methods=['GET'])
Beispiel #25
0
import flask
from flask import Flask, request, url_for
from flask_peewee.rest import RestAPI, RestResource
from models.Email import *
from models.Category import *
from models.Form import *

app = Flask(__name__)
api = RestAPI(app)

api.register(Email, UserResource)
api.register(Category)
api.register(Form)

# configure the urls
api.setup()

if __name__ == '__main__':
    app.run(port=int(os.getenv('PORT', 5000)), host="0.0.0.0", debug=True)
Beispiel #26
0
class EResource(RestResource):
    pass

class FResource(RestResource):
    include_resources = {'e': EResource}

# rest api stuff
dummy_auth = Authentication(protected_methods=[])
user_auth = UserAuthentication(auth)
admin_auth = AdminAuthentication(auth)
api_key_auth = APIKeyAuthentication(APIKey, ['GET', 'POST', 'PUT', 'DELETE'])

api = RestAPI(app, default_auth=user_auth)

api.register(Message, RestrictOwnerResource)
api.register(User, UserResource, auth=admin_auth)
api.register(Note)
api.register(TestModel, auth=api_key_auth)
api.register(AModel, AResource, auth=dummy_auth)
api.register(BModel, BResource, auth=dummy_auth)
api.register(CModel, CResource, auth=dummy_auth)

api.register(EModel, EResource, auth=dummy_auth)
api.register(FModel, FResource, auth=dummy_auth)


# views
@app.route('/')
def homepage():
    return Response()
Beispiel #27
0
from flask_peewee.rest import RestAPI, RestResource, UserAuthentication, AdminAuthentication, RestrictOwnerResource

from app import app
from auth import auth
from models import User, Message#, Relationship


user_auth = UserAuthentication(auth)
admin_auth = AdminAuthentication(auth)

# instantiate our api wrapper
api = RestAPI(app, default_auth=user_auth)


class UserResource(RestResource):
    exclude = ('password', 'email',)


class MessageResource(RestrictOwnerResource):
    owner_field = 'user'
    include_resources = {'user': UserResource}


# register our models so they are exposed via /api/<model>/
api.register(User, UserResource, auth=admin_auth)
api.register(Message, MessageResource)
Beispiel #28
0
        return self.model.select()

admin = Admin(app, auth)
admin.register(Contents, ContentsAdmin)

admin.setup()

# instantiate the user auth
user_auth = UserAuthentication(auth)
admin_auth = AdminAuthentication(auth)

# create a RestAPI container
api = RestAPI(app, default_auth=user_auth)

#register the Content model
api.register(Contents, ContentsResource, auth=admin_auth)
api.setup()

# customize template tag
def date_now(value):
    return datetime.datetime.now().strftime(value).decode('utf-8')

app.jinja_env.filters['date_now'] = date_now


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.errorhandler(404)
def page_not_found(e):
Beispiel #29
0
        'city': CityResource,
    }

class CarBrandResource(RestResource):
    exclude = ()

class CarSeriesResource(RestResource):
    exclude = ()
    owner_field = 'brand'
    include_resources = {
        'brand': CarBrandResource,
    }

class CarModelResource(RestResource):
    exclude = ()
    owner_field = 'series'
    include_resources = {
        'series': CarSeriesResource,
    }

# register our models so they are exposed via /api/<model>/
api.register(User, UserResource, auth=admin_auth)
api.register(Relationship, RelationshipResource)
api.register(Message, MessageResource)

api.register(City, CityResource)
api.register(Pinche, PincheResource)
api.register(CarBrand, CarBrandResource)
api.register(CarSeries, CarSeriesResource)
api.register(CarModel, CarModelResource)
Beispiel #30
0
from routes import route

DATABASE = {
    # 数据库名
    'name': 'gcl',
    # 数据库引擎,不用更改
    'engine': 'peewee.MySQLDatabase',
    # 用户名
    'user': '******',
    # 密码
    'passwd': 'gcl',
}

app = Flask(__name__)
app.config.from_object(__name__)
app.config['DEBUG'] = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)
db = Database(app)
CORS(app, resources='/*')
auth = Auth(app, db)
user_auth = GclAuthentication(auth)
api = RestAPI(app, default_auth=user_auth)

if __name__ == '__main__':
    models = setup.setup()
    # 注册api,发现只有在app.py里注册才能正常使用
    for klass in models:
        api.register(klass, GclRestResource)
    app.register_blueprint(route)
    api.setup()
    app.run()
Beispiel #31
0
# -*- coding: utf-8 -*-
from flask_peewee.rest import RestAPI, RestResource, UserAuthentication, AdminAuthentication

from app import app
from auth import auth
from models import User

user_auth = UserAuthentication(auth)
admin_auth = AdminAuthentication(
    auth, protected_methods=['GET', 'POST', 'PUT', 'DELETE'])

api = RestAPI(app, default_auth=user_auth)


class UserResource(RestResource):
    exclude = (
        'password',
        'email',
    )


api.register(User, UserResource, auth=admin_auth, allowed_methods=['GET'])
api.setup()
Beispiel #32
0
        next = previous = ''

        if current_page > 1:
            request_arguments[var] = current_page - 1
            previous = url_for(self.get_url_name('api_list'),
                               **request_arguments)
        if current_page < paginated_query.get_pages():
            request_arguments[var] = current_page + 1
            next = url_for(self.get_url_name('api_list'), **request_arguments)

        meta_v = {
            'model': self.get_api_name(),
            'page': current_page,
            'previous': previous,
            'next': next,
            'total': Email.select().count()
        }

        flask.jsonify(meta_v)
        return meta_v


# register our models so they are exposed via /api/<model>/
api.register(Email, UserResource)

# configure the urls
api.setup()

if __name__ == '__main__':
    app.run(port=int(os.getenv('PORT', 5000)), host="0.0.0.0", debug=True)
Beispiel #33
0
# -*- coding: utf-8 -*-
from flask_peewee.rest import RestAPI, RestResource, UserAuthentication
from web.app import app, auth
from web.model import Label, Inspiration, LabelInspirationRelationShip


user_auth = UserAuthentication(auth)

api = RestAPI(app, default_auth=user_auth)

class InspirationResource(RestResource):
    def prepare_data(self, obj, data):
        data["labels"] = [l.to_json() for l in obj.labels]
        return data
api.register(Inspiration, InspirationResource)

class LabelInspirationRelationShipResource(RestResource):
    paginate_by = 200
    def prepare_data(self, obj, data):
        inspiration_id = data["inspiration"]
        inspiration = Inspiration.select().where(Inspiration.id == inspiration_id).first()
        data["inspiration"] = inspiration.to_json()
        return data
api.register(LabelInspirationRelationShip, LabelInspirationRelationShipResource)



# setup user
register_class = [Label, auth.User]
for klass in register_class:
    api.register(klass)
Beispiel #34
0
class UserResource(RestResource):
    exclude = ('password', 'email',)
    
    def get_query(self):
        return User.filter(active=True)


# rest api stuff
user_auth = UserAuthentication(auth)
admin_auth = AdminAuthentication(auth)
api_key_auth = APIKeyAuthentication(APIKey, ['GET', 'POST', 'PUT', 'DELETE'])

api = RestAPI(app, default_auth=user_auth)

api.register(Message, RestrictOwnerResource)
api.register(User, UserResource, auth=admin_auth)
api.register(Note)
api.register(TestModel, auth=api_key_auth)


# views
@app.route('/')
def homepage():
    return Response()

@app.route('/private/')
@auth.login_required
def private_timeline():
    return Response()
Beispiel #35
0
from rq.job import Job
from worker import conn
from flask_peewee.db import SqliteDatabase
from flask_peewee.rest import RestAPI

from models.company import Company
from models.load import Load
from models.user import User
from models.location import Location

app = Flask(__name__)
app.config.from_object(__name__)
q = Queue(connection=conn)

api = RestAPI(app)
api.register(User)
api.register(Company)
api.register(Load)
api.register(Location)
api.setup()

@app.route('/', methods=['GET', 'POST'])
def index():
    results = {}
    # if request.method == "POST":
    #     # get url that the person has entered
    #     url = request.form['url']
    #     if 'http://' not in url[:7]:
    #         url = 'http://' + url
        # job = q.enqueue_call(
        #     func="hello.count_and_save_words", args=(url,), result_ttl=5000
Beispiel #36
0
    include_resources = {
        'canton': CantonResource,
        'council': CouncilResource,
        'party': PartyResource,
    }

class PromiseResource(RestResource):
    include_resources = {
        'councillor': CouncillorResource
    }

class DecisionResource(RestResource):
    exclude = ('councillor')

class CommentResource(RestResource):
    include_resources = {
        'promise': PromiseResource,
        'decision': DecisionResource
    }
    paginate_by = None

class UserResource(RestResource):
    exclude = ('password', 'email',)

# register our models so they are exposed via /api/<model>/
api.register(Councillor, CouncillorResource)
api.register(Promise, PromiseResource)
api.register(Decision, DecisionResource)
api.register(Comment, CommentResource)
api.register(auth.User, UserResource, auth=admin_auth)
Beispiel #37
0
from flask_peewee.rest import RestAPI

from app import app # our project's Flask app

# instantiate our api wrapper
api = RestAPI(app)

# register our models so they are exposed via /api/<model>/
api.register(User)
api.register(Relationship)
api.register(Message)

# configure the urls
api.setup()
Beispiel #38
0
class MessageResource(RestrictOwnerResource):
    owner_field = 'user'
    include_resources = {'user': UserResource}

class RelationshipResource(RestrictOwnerResource):
    owner_field = 'from_user'
    include_resources = {
        'from_user': UserResource,
        'to_user': UserResource,
    }
    paginate_by = None

class CityResource(RestResource):
    exclude = ()

class PincheResource(RestResource):
    exclude = ('pub_date', )
    owner_field = 'city'
    include_resources = {
        'city': CityResource,
    }

# register our models so they are exposed via /api/<model>/
api.register(User, UserResource, auth=admin_auth)
api.register(Relationship, RelationshipResource)
api.register(Message, MessageResource)

api.register(City, CityResource)
api.register(Pinche, PincheResource)
Beispiel #39
0
    blog = peewee.ForeignKeyField(Blog, related_name='posts')
    title = peewee.CharField()


api = RestAPI(app)


class BlogResource(RestResource):
    pass


class PostResource(RestResource):
    pass


api.register(Blog, BlogResource)
api.register(Post, PostResource)

api.setup()

######################################
# create the swagger api end point
######################################

swagger = Swagger(api)
swagger.setup()

swaggerUI = SwaggerUI(app)
swaggerUI.setup()

if __name__ == '__main__':
Beispiel #40
0
__author__ = 'ajboehmler'

from flask_peewee.rest import RestAPI, RestResource, UserAuthentication

from app import app
from auth import auth
from models import User

user_auth = UserAuthentication(auth)

# instantiate our api wrapper and tell it to use HTTP basic auth using
# the same credentials as our auth system.  If you prefer this could
# instead be a key-based auth, or god forbid some open auth protocol.
api = RestAPI(app, default_auth=user_auth)


class UserResource(RestResource):
    exclude = ('password', 'email',)

# register our models so they are exposed via /api/<model>/
api.register(User, UserResource, auth=user_auth)
Beispiel #41
0
from flask_peewee.rest import RestAPI, RestResource
from app import app
from models import *

# from auth import auth

# user_auth = UserAuthentification(auth)

api = RestAPI(app)  # To Add for authorization: default_auth=user_auth

api.register(ExploreCard)
Beispiel #42
0
        return True


# create a special resource for users that excludes email and password
class UserResource(RestResource):
    exclude = ('password', 'email',)

# create an Auth object for use with our flask app and database wrapper
auth = Auth(app, db)

# instantiate the user auth
user_auth = UserAuthentication(auth, protected_methods=['GET', 'POST', 'PUT', 'DELETE'])
# create a RestAPI container
api = RestAPI(app, default_auth=user_auth)
# register the models
api.register(Card, CardResource, auth=user_auth)
api.register(CardGroup, auth=user_auth)
api.register(auth.User, UserResource, auth=user_auth)
api.setup()


admin = Admin(app, auth, branding='A2Billing API Admin Site')
admin.register(Card, CardAdmin)
admin.register(CardGroup, CardGroupAdmin)
auth.register_admin(admin)
admin.setup()


if __name__ == '__main__':
    auth.User.create_table(fail_silently=True)
    # Note.create_table(fail_silently=True)
Beispiel #43
0
from flask_peewee.rest import (RestAPI, RestResource, UserAuthentication,
        AdminAuthentication, RestrictOwnerResource)

from app import app
from auth import auth
from models import User, Relationship


user_auth = UserAuthentication(auth)
admin_auth = AdminAuthentication(auth)

api = RestAPI(app, default_auth=user_auth)


class UserResource(RestResource):
    exclude = ('password', 'email',)


class RelationshipResource(RestrictOwnerResource):
    owner_field = 'from_user'
    include_resources = {
        'from_user': UserResource,
        'to_user': UserResource,
    }
    paginate_by = None


# register our models so they are exposed via /api/<model>/
api.register(User, UserResource, auth=admin_auth)
api.register(Relationship, RelationshipResource)
Beispiel #44
0
admin_auth = AdminAuthentication(auth)

# instantiate our api wrapper
api = RestAPI(app, default_auth=user_auth)


class UserResource(RestResource):
    exclude = (
        'password',
        'email',
    )


class MessageResource(RestrictOwnerResource):
    owner_field = 'user'
    include_resources = {'user': UserResource}


class RelationshipResource(RestrictOwnerResource):
    owner_field = 'from_user'
    include_resources = {
        'from_user': UserResource,
        'to_user': UserResource,
    }


# register our models so they are exposed via /api/<model>/
api.register(User, UserResource, auth=admin_auth)
api.register(Relationship, RelationshipResource)
api.register(Message, MessageResource)
Beispiel #45
0
    def get_api_name(self):
        """Pluralize the name based on the model."""
        return slugify(self.model.__name__ + 's')


class BlogResource(AppRestResource):
    pass


class PostResource(RestResource):
    pass


api = RestAPI(app)
api.register(Blog, BlogResource, Authentication())
api.register(Post, PostResource, Authentication())
api.setup()

######################################
# create the swagger api end point
######################################

swagger = Swagger(api)
swagger.setup()

swagger2 = Swagger(api, version="1.1", swagger_version="2.0", name="spec2")
swagger2.setup(prefix="spec2")

swaggerUI = SwaggerUI(app)
swaggerUI.setup()
Beispiel #46
0
from flask_peewee.rest import RestAPI, RestResource, UserAuthentication, \
    AdminAuthentication

from wx.app import app
from wx.auth import auth
from wx.models import User, Location, Station, Report, Value


# See: http://flask-peewee.readthedocs.org/en/latest/rest-api.html
# Read-only for now. Use the following:
# user_auth = UserAuthentication(auth)
# admin_auth = AdminAuthentication(auth)

api = RestAPI(app)


class UserResource(RestResource):
    exclude = ('password', 'email',)


api.register(User, UserResource)
api.register(Location)
api.register(Station)
api.register(Report)
api.register(Value)
Beispiel #47
0
    def authorize(self):
        return True
        # return session.get('magic', '') == 'a'


class ScriptResource(SessionAuthResource):
    pass


class ReportResource(SessionAuthResource):
    paginate_by = 100

    def get_query(self):
        if request.args.get('method', '') == "listURI":
            # monkey patch fields
            self._fields = {self.model: ['latest', 'count', 'uri']}
            return Report.select(
                Report.uri,
                fn.Count(Report.id).alias('count'),
                fn.Max(Report.created).alias('latest')).group_by(
                    Report.uri).order_by(fn.Max(Report.created).desc())
        else:
            self._fields = {self.model: self.model._meta.get_field_names()}
            return SessionAuthResource.get_query(self)


api = RestAPI(app)
api.register(Report, ReportResource)
api.register(Script, ScriptResource)
api.setup()
Beispiel #48
0
from flask import Flask
from flask_peewee.db import Database
from models import *
from flask_peewee.rest import RestAPI

DATABASE = {
        'name': 'openmrs',
        'engine': 'peewee.MySQLDatabase',
        'user': '******',
        'passwd': 'GlobalHeedPFC1'
}
DEBUG = True

app = Flask(__name__)
app.config.from_object(__name__)

# Instantiate the DB wrapper
db = Database(app)

# Expose content via REST API
api = RestAPI(app)
api.register(Person)
api.setup()

if __name__ == '__main__':
    app.run()
Beispiel #49
0
from flask_peewee.rest import RestAPI, RestResource, UserAuthentication, AdminAuthentication, RestrictOwnerResource

from app import app
from auth import auth

from models import User, News, OursNews

user_auth = UserAuthentication(auth)
admin_auth = AdminAuthentication(auth)

# instantiate our api wrapper
api = RestAPI(app, default_auth=user_auth)


class UserResource(RestResource):
    exclude = ()


class NewsResource(RestResource):
    exclude = ()


class OursNewsResource(RestResource):
    exclude = ()


api.register(User, UserResource, auth=admin_auth)
api.register(News, NewsResource)
api.register(OursNews, OursNewsResource)
Beispiel #50
0
from app import app
from models import db
from models import Person, PersonAdmin
from models import Company, CompanyAdmin
from models import Payment, PaymentAdmin
from models import Tariff, TariffAdmin
from models import Point, PointAdmin
from models import Bike, BikeAdmin
from models import ReservationState, ReservationStateAdmin
from models import Reservation, ReservationAdmin

auth = Auth(app, db)

# REST API
api = RestAPI(app)
api.register(Person)
api.register(Company)
api.register(Payment)
api.register(Tariff)
api.register(Point)
api.register(Bike)
api.register(ReservationState)
api.register(Reservation)
api.setup()

# REST ADMIN
admin = Admin(app, auth)
admin.register(Person, PersonAdmin)
admin.register(Company, CompanyAdmin)
admin.register(Payment, PaymentAdmin)
admin.register(Tariff, TariffAdmin)
Beispiel #51
0
    exclude = (
        'password',
        'email',
    )


# class LogrefillResource(RestResource):

#     def prepare_data(self, obj, data):
#         data["credit"] = str(data["credit"])
#         return data

# instantiate the user auth
user_auth = UserAuthentication(
    auth, protected_methods=['GET', 'POST', 'PUT', 'DELETE'])

# create a RestAPI container
api = RestAPI(app, default_auth=user_auth)
# register the models
api.register(Card, CardResource, auth=user_auth)
api.register(CardGroup, auth=user_auth)
api.register(Callerid, auth=user_auth)
api.register(Logrefill, auth=user_auth)
api.register(Logpayment, auth=user_auth)
api.register(Call, auth=user_auth)
api.register(Country, auth=user_auth)
api.register(Charge, auth=user_auth)
# api.register(Did, auth=user_auth)
# api.register(DidDestination, auth=user_auth)
api.register(auth.User, UserResource, auth=user_auth)
Beispiel #52
0
class SessionAuthResource(RestResource):
    def authorize(self):
        return True
        # return session.get('magic', '') == 'a'


class ScriptResource(SessionAuthResource):
    pass


class ReportResource(SessionAuthResource):
    paginate_by = 100

    def get_query(self):
        if request.args.get('method', '') == "listURI":
            # monkey patch fields
            self._fields = {self.model: ['latest', 'count', 'uri']}
            return Report.select(Report.uri, fn.Count(Report.id).alias(
                'count'), fn.Max(Report.created).alias('latest')).group_by(
                Report.uri).order_by(fn.Max(Report.created).desc())
        else:
            self._fields = {self.model: self.model._meta.get_field_names()}
            return SessionAuthResource.get_query(self)


api = RestAPI(app)
api.register(Report, ReportResource)
api.register(Script, ScriptResource)
api.setup()
Beispiel #53
0

user_auth = UserAuthentication(auth)
admin_auth = AdminAuthentication(auth)

api = RestAPI(app, default_auth=user_auth)


class UserResource(RestResource):
	exclude = ('password', 'email',)


class UserRelationshipResource(RestResource):
	exclude = ()


class UserGithubResource(RestResource):
	exclude = ('github_access_token',)


class FavoriteResource(RestResource):
    def prepare_data(self, obj, data):
        return data


# register our models so they are exposed via /api/<model>/
api.register(User, UserResource, auth=admin_auth)
api.register(UserGithub, UserGithubResource, auth=admin_auth)
api.register(UserRelationship, UserRelationshipResource, auth=user_auth)
api.register(UserGistFavorite, FavoriteResource, auth=user_auth)
Beispiel #54
0
from auth import auth

from model import Goods, User, Reviews, Photo

from flask_peewee.rest import RestAPI, UserAuthentication, RestResource


class ForeignResource(RestResource):
    exclude = (
        'amount',
        'size',
        'photo',
    )


class ForeignResource1(RestResource):
    fields = ('name')


class MessageResource(RestResource):
    include_resources = {'goods': ForeignResource, 'author': ForeignResource}


# create a RestAPI container
user_auth = UserAuthentication(auth)

# create a RestAPI container
api = RestAPI(app, default_auth=user_auth)
api.register(Goods)
api.register(User)
api.register(Reviews, MessageResource)
Beispiel #55
0
            break
        print "yrs"
        a['type'] = obj_type
        a['id'] = a[obj_type+'ID']
        a['text'] = a[obj_type]
        print "end"
        r.append(a)
    return r

app = Flask(__name__)

class SubjectsResource(RestResource):
    paginate_by = 200

api = RestAPI(app)
api.register(Departments, SubjectsResource)
api.register(Courses)
api.register(Subjects, SubjectsResource)
api.register(Colleges, SubjectsResource)

api.setup()


@app.route('/')
def index():
    return render_template('latech.html',
                           require=url_for('static', filename='require.min.js'),
                           js=url_for('static', filename='latech.js'),
                           css=url_for('static', filename='latech.css'),
                           mainjs=url_for('static', filename='main.js'))
Beispiel #56
0
                   aws_secret_access_key = os.environ['AWS_SECRET_ACCESS_KEY'],
                   region_name           = os.environ['AWS_DEFAULT_REGION'])

queue_url = os.environ['QUEUE_URL']
version='1.00'

start_time = datetime.now()
app = Flask(__name__)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False


# instantiate our api wrapper
api = RestAPI(app)

# register our models so they are exposed via /api/<model>/
api.register(Message)
api.register(Instance)

# configure the urls
api.setup()


@app.route('/')
def test():
    return "flask is running for {} seconds...".format(datetime.now() - start_time)


@app.route('/add', methods=['GET'])
def add_managed_instance():
    name = request.args.get('name')
    private_ns = request.args.get('private_ns')
Beispiel #57
0
admin.register(Note, NoteAdmin)
admin.register(User, UserAdmin)
auth.register_admin(admin)
admin.setup()


class UserResource(RestResource):
    exclude = ("password", "email")


class NoteResource(RestrictOwnerResource):
    owner_field = "user"


user_auth = UserAuthentication(auth)
admin_auth = AdminAuthentication(auth)

api = RestAPI(app, default_auth=user_auth)
api.register(User, UserResource, auth=admin_auth)
api.register(Note, NoteResource)
api.setup()


@app.route("/version")
def version():
    return "2.1"


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=app.config["PORT"])