def setup(app):
    from . import RestAPI_patch
    rest_api = RestAPI(app, default_auth=Authentication(protected_methods=[]))

    # register user api
    for api in APIRestResource.__subclasses__():
        register_api(rest_api, api)
    api_info(app)

    rest_api.setup()
Exemple #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()
Exemple #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()
Exemple #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()
Exemple #5
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
Exemple #6
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()
Exemple #7
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)
Exemple #8
0
    Thanks to this, an item can be bought by several different users.
    """
	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)
Exemple #9
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)
Exemple #10
0
from flask_peewee.rest import RestAPI, RestResource, UserAuthentication

from app import app
from sync_log import SyncLog
from auth import auth
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)
Exemple #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()
Exemple #12
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)
Exemple #13
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)
Exemple #14
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)
Exemple #15
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)
Exemple #16
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)
Exemple #17
0
from rui.series.model import Fansub
from rui.series.model import ScrapParam
from rui.series.model import ScrapParamTemplate
from rui.series.model import Notification
from rui.series.model import db

from rui.config import data as dataConfig

from rui.series.resources import NotificationResource

# Define the WSGI application object
app = Flask(__name__)
app.config["DATABASE"] = {"name": dataConfig["path"], "engine": "peewee.SqliteDatabase"}
app.config["SECRET_KEY"] = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'
# instantiate our api wrapper
api = RestAPI(app)

# Admin area


db = Database(app)

# needed for authentication
auth = Auth(app, db)
# auth.User.create_table(fail_silently=True)

demo = auth.User(username="******", email="", admin=True, active=True)
demo.set_password("sonata")
demo.save()

admin = Admin(app, auth)
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)

Exemple #19
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}


class RelationshipResource(RestrictOwnerResource):
    owner_field = 'from_user'
    include_resources = {
        'from_user': UserResource,
        'to_user': UserResource,
    }
Exemple #20
0
class CResource(RestResource):
    include_resources = {'b': BResource}

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('/')
Exemple #21
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, City, Pinche
from models import CarBrand, CarSeries, CarModel

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}

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

class CityResource(RestResource):
    exclude = ()
Exemple #22
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)
Exemple #23
0
from flask_peewee.rest import RestAPI, UserAuthentication
from psyc import app
#from models.models import Note
import psyc.models.processor as processor
from auth import auth

user_auth = UserAuthentication(auth)
api = RestAPI(app, default_auth=user_auth)
#api.register(processor.Processor, processor.ProcessorResource)
api.setup()
Exemple #24
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()
Exemple #25
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()
Exemple #26
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)
Exemple #27
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)
def create_app():
    app = Flask(__name__)  # Создаем экземпляр класса Flask-приложения
    app.url_map.strict_slashes = local_settings.TRAILING_SLASH  # Указываем игнорирововать слеша в конце url
    app.config.from_object(
        local_settings)  # Передаём остальные настройки в приложение
    return app


APP = create_app()  # Инициируем приложение

DB = Database(
    APP
)  # Инициируем работу с БД. Тут же создаюётся таблицы, если их нет в БД.
init_models(DB)

API = RestAPI(APP)  # Инициируем RestAPI от peewee
init_api(API)

ADMIN = init_admin(APP, DB)  # Инициируем Админку

import ui.root  # Импортируем view для главной страницы

# Api на flask_restful и роуты для API
from flask_restful import Api

api = Api(APP)

from services.product import GetProducts, AddProduct, DeleteProduct, UpdateProduct
api.add_resource(GetProducts, '/product/get')
api.add_resource(AddProduct, '/product/add/<int:category_id>')
api.add_resource(DeleteProduct, '/product/delete/<int:product_id>')
Exemple #29
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# oneesama - a video playback server
#
# Author: slowpoke <*****@*****.**>
#
# This program is Free Software under the non-terms
# of the Anti-License. Do whatever the f**k you want.

from ..app import app
from ..auth import user_auth
from ..models import models
from .resources import resources

from . import resources, views

from flask_peewee.rest import RestAPI, RestResource

api = RestAPI(app, default_auth=user_auth)


def register_all():
    resource_table = {}
    for resource in resources:
        resource_table[resource.__name__] = resource
    for model in models:
        resource = resource_table.get("{}Resource".format(model.__name__),
                                      RestResource)
        api.register(model, resource)
    api.setup()
Exemple #30
0
from rq import Queue
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(
Exemple #31
0
admin.register_panel('Notes', NotePanel)


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():
Exemple #32
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()
Exemple #33
0
from flask_peewee.rest import RestAPI, RestResource, UserAuthentication, AdminAuthentication, RestrictOwnerResource

from app import app
from auth import auth
from models import Councillor, Promise, Decision, Comment

api = RestAPI(app)
admin_auth = AdminAuthentication(auth)

class CantonResource(RestResource):
    exclude = ()

class CouncilResource(RestResource):
    exclude = ()

class PartyResource(RestResource):
    exclude = ()

class CouncillorResource(RestResource):
    include_resources = {
        'canton': CantonResource,
        'council': CouncilResource,
        'party': PartyResource,
    }

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

class DecisionResource(RestResource):
app = Flask(__name__)


class Blog(peewee.Model):
    title = peewee.CharField()
    created = peewee.DateTimeField()
    modified = peewee.DateTimeField()


class Post(peewee.Model):
    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()
Exemple #35
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, City, Pinche


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}

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

class CityResource(RestResource):
    exclude = ()
Exemple #36
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)
Exemple #37
0
    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():
Exemple #38
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)
from flask_peewee.rest import RestAPI
import psycopg2

from flask_limiter import Limiter
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"]
Exemple #40
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)
Exemple #41
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'])
Exemple #42
0
from flask_peewee.rest import RestAPI, RestResource, UserAuthentication, AdminAuthentication, RestrictOwnerResource

from gistsurfr.app import app
from gistsurfr.auth import auth
from gistsurfr.models import User, UserRelationship, UserGithub, UserGistFavorite


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>/
Exemple #43
0
 def __init__(self):
     # Initialize flask
     self.flask = Flask('data_store')
     self.api = RestAPI(self.flask)
Exemple #44
0
from angular_flask import app

from flask_peewee.db import Database
from flask_peewee.rest import RestAPI

db = Database(app)

api_manager = RestAPI(app)

Exemple #45
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()
Exemple #46
0
                a = val
            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'))
Exemple #47
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)
Exemple #48
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"])
Exemple #49
0
    """Application REST Resource."""

    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)
Exemple #50
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)

Exemple #51
0
assets = Environment(app)
assets.url = app.static_url_path

# css_bundle = Bundle('css/home.css.sass', filters='sass', output='all.css')
# assets.register('css_all', css_bundle)

# js_bundle = Bundle('js/test.js.coffee', filters='coffeescript', output='all.js')
# assets.register('js_all', js_bundle)

# Instantaite Flask Peewee Database ORM
db = Database(app)
db.database.get_conn().set_client_encoding('UTF8')

# Instatiate Flask Peewee REST API
api = RestAPI(app)

# Transaction
db.database.set_autocommit(True)

# Import All Models and Controllers
from app import database_views
from app import decorators
from app.models import Topic
from app.models import Frame
from app.models import User
from app.models import Speech
from app.models import SpeechTopic
from app.controllers import Topic
from app.controllers import Frame
from app.controllers import User
Exemple #52
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()
Exemple #53
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)
Exemple #54
0
        Gotta super.
        """
        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()
Exemple #55
0
# aws sqs parameters
sqs = boto3.client('sqs',
                   aws_access_key_id     = os.environ['AWS_ACCESS_KEY_ID'],
                   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'])
Exemple #56
0
        if match == None:
            return "*****@*****.**"
        return match.group(0)

    def politicalnewsbot_link(self):
        return "https://mail.google.com/mail/u/2/#inbox/%[email protected]" % self.message_id

    def politicalnewsbotnewyork_link(self):
        return "https://mail.google.com/mail/u/inbox/%[email protected]" % self.message_id

    @classmethod
    def unique_email_addresses(cls):
        return {x.email() for x in cls.select()}


api = RestAPI(app)


class UserResource(RestResource):
    exclude = ('sender', 'message_id', 'serialized_json', 'message_labels')

    def get_request_metadata(self, paginated_query):
        var = paginated_query.page_var
        request_arguments = request.args.copy()
        current_page = paginated_query.get_page()
        next = previous = ''

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