Ejemplo n.º 1
0
    def setUp(self):
        class CustomParser1(parsers.BaseParser):
            media_type = '*/*'

            def parse(self, stream, media_type, content_length=None):
                return 'custom parser 1'

        class CustomParser2(parsers.BaseParser):
            media_type = '*/*'

            def parse(self, stream, media_type, content_length=None):
                return 'custom parser 2'

        app = FlaskAPI(__name__)
        app.config['DEFAULT_PARSERS'] = [CustomParser1]

        @app.route('/custom_parser_1/', methods=['POST'])
        def custom_parser_1():
            return {'data': request.data}

        @app.route('/custom_parser_2/', methods=['POST'])
        @set_parsers([CustomParser2])
        def custom_parser_2():
            return {'data': request.data}

        @app.route('/custom_parser_2_as_args/', methods=['POST'])
        @set_parsers(CustomParser2, CustomParser1)
        def custom_parser_2_as_args():
            return {'data': request.data}

        self.app = app
Ejemplo n.º 2
0
    def setUp(self):
        class CustomRenderer1(renderers.BaseRenderer):
            media_type = 'application/example1'

            def render(self, data, media_type, **options):
                return 'custom renderer 1'

        class CustomRenderer2(renderers.BaseRenderer):
            media_type = 'application/example2'

            def render(self, data, media_type, **options):
                return 'custom renderer 2'

        app = FlaskAPI(__name__)
        app.config['DEFAULT_RENDERERS'] = [CustomRenderer1]
        app.config['PROPAGATE_EXCEPTIONS'] = True

        @app.route('/custom_renderer_1/', methods=['GET'])
        def custom_renderer_1():
            return {'data': 'example'}

        @app.route('/custom_renderer_2/', methods=['GET'])
        @set_renderers([CustomRenderer2])
        def custom_renderer_2():
            return {'data': 'example'}

        @app.route('/custom_renderer_2_as_args/', methods=['GET'])
        @set_renderers(CustomRenderer2)
        def custom_renderer_2_as_args():
            return {'data': 'example'}

        self.app = app
Ejemplo n.º 3
0
    def test_render_browsable_encoding(self):
        app = FlaskAPI(__name__)

        @app.route('/_love', methods=['GET'])
        def love():
            return {"test": "I <3 Python"}

        with app.test_client() as client:
            response = client.get('/_love',
                                  headers={"Accept": "text/html"})
            html = str(response.get_data())
            self.assertTrue('I &lt;3 Python' in html)
            self.assertTrue('<h1>Love</h1>' in html)
            self.assertTrue('/_love' in html)
Ejemplo n.º 4
0
    def test_render_browsable_linking(self):
        app = FlaskAPI(__name__)

        @app.route('/_happiness', methods=['GET'])
        def happiness():
            return {"url": "http://example.org",
                    "a tag": "<br />"}

        with app.test_client() as client:
            response = client.get('/_happiness',
                                  headers={"Accept": "text/html"})
            html = str(response.get_data())
            self.assertTrue('<a href="http://example.org">http://example.org</a>' in html)
            self.assertTrue('&lt;br /&gt;'in html)
            self.assertTrue('<h1>Happiness</h1>' in html)
            self.assertTrue('/_happiness' in html)
Ejemplo n.º 5
0
def _run_mocked():
    app = FlaskAPI(__name__)
    app.url_map.converters['regex'] = RegexConverter
    app.debug = True
    app.register_blueprint(api, url_prefix=DEFAULT_PREFIX)

    @app.after_request
    def print_mock(response):
        from pprint import pformat
        # noinspection PyUnresolvedReferences
        logger.debug(pformat(dagor_focus.mock_calls, indent=4))
        return response

    app.run("0.0.0.0")
Ejemplo n.º 6
0
from flask.templating import render_template
from flask_api import FlaskAPI
from flask_api.decorators import set_renderers
from flask_api.renderers import HTMLRenderer
application = FlaskAPI(__name__)


@application.route("/", methods=['GET'])
@application.route("/home", methods=['GET'])
@set_renderers(HTMLRenderer)
def home():
    params_tpl = {}
    return render_template('index.html', params_tpl=params_tpl)


@application.route("/login", methods=['GET'])
@set_renderers(HTMLRenderer)
def login():
    params_tpl = {}
    return render_template('login.html', params_tpl=params_tpl)


@application.route("/panels_wells", methods=['GET'])
@set_renderers(HTMLRenderer)
def panels_wells():
    params_tpl = {}
    return render_template('panels-wells.html', params_tpl=params_tpl)


@application.route("/buttons", methods=['GET'])
@set_renderers(HTMLRenderer)
Ejemplo n.º 7
0
from flask import request, url_for, render_template
from flask_api import FlaskAPI, status, exceptions

app = FlaskAPI(__name__)


import pickle
loaded_model = pickle.load(open('finalized_model_svm_2.sav', 'rb'))

# calculate TF
def compute_TF(word_dict, bow):
    tf_dict = {}
    bow_count = len(bow)
    for word in word_dict:
        tf_dict[word] = word_dict[word] / (float(bow_count)+1)

    return tf_dict


def compute_IDF(doc_list):
    import math
    idf_dict = {}
    N = len(doc_list)

    # count number of documents that contain this word
    idf_dict = dict.fromkeys(doc_list[0].keys(), 0)
    for doc in doc_list:
        for word in doc:
            if doc[word] > 0:
                idf_dict[word] += 1
Ejemplo n.º 8
0
from flask_api import FlaskAPI
import os

app = FlaskAPI("Optic")


@app.route('/')
def index():
    return "hi world"


app.run(port=os.environ['OPTIC_API_PORT'] if 'OPTIC_API_PORT' in
        os.environ else 4003)
Ejemplo n.º 9
0
from flask import request, jsonify
from flask_api import FlaskAPI
from flask_cors import CORS, cross_origin
import random
from statistics import mean 
from datetime import datetime

app = FlaskAPI(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

criterio = 1
seleccion = 1
data = []
generacion = 0
tam_poblacion = 10
tam_solucion = 4

class Nodo:

    def __init__(self, solucion = [], fitness = 0):
        self.solucion = solucion
        self.fitness = fitness

def mutar(solucion):
    if random.uniform(0, 1) <= 0.5:
        index = 0
        while index < tam_solucion:
            if random.uniform(0, 1) <= 0.5:
                solucion[index] = round(random.uniform(-2, 2), 5)
            index += 1
Ejemplo n.º 10
0
from flask_api import FlaskAPI
from flask import request
from flask_cors import CORS, cross_origin

import os

from datetime import datetime
import moment

from .blueprints.ranking import ranking_blueprint
from .blueprints.retencao import retencao_blueprint

# def create_app(setting=None):
    
# Inicia uma aplicacap flask
app = FlaskAPI(__name__)

if 'FLASK_CONFIG' in os.environ.keys():
    app.config.from_object('app.settings.' + os.environ['FLASK_CONFIG'])
else:
    app.config.from_object('app.settings.Development')


# if setting:
#     # atribui as configuracoes na aplicacao
#     app.config.from_object(setting)

# configura cors
# Essa configuracao permite que todas as requisicoes possam ser feitas,
# eliminando os erros de Requests que ocorrem em alguns navegadores
cors = CORS(app, resources={r"/*": {"origins": "*"}})
Ejemplo n.º 11
0
logger.debug("CONFIGURATION SETTING[aws_region]: %s " % config.get_aws_region())
logger.debug("CONFIGURATION SETTING[block_cypher_token]: %s " % config.get_block_cypher_token())
logger.debug("CONFIGURATION SETTING[block_cypher_url]: %s " % config.get_block_cypher_url())
logger.debug("CONFIGURATION SETTING[coin_network]: %s " % config.get_coin_network())
logger.debug("CONFIGURATION SETTING[db_url]: %s " % config.get_db_url())
logger.debug("CONFIGURATION SETTING[debug_log]: %s " % config.get_debug_log())
logger.debug("CONFIGURATION SETTING[key_id]: %s " % config.get_key_id())
logger.debug("CONFIGURATION SETTING[local_db_url]: %s " % config.get_local_db_url())
logger.debug("CONFIGURATION SETTING[local_server_url]: %s " % config.get_local_server_url())
logger.debug("CONFIGURATION SETTING[remote_db_url]: %s " % config.get_remote_db_url())
logger.debug("CONFIGURATION SETTING[remote_server_url]: %s " % config.get_remote_server_url())
logger.debug("CONFIGURATION SETTING[wallet_type]: %s " % config.get_wallet_type())
logger.debug("-------------------------ENVIRONMENT--------------------------")

keyId = config.get_key_id()
application = FlaskAPI(__name__)
wallet = wallet.create_wallet(config.get_wallet_type(), config, logger)
account_service = AccountService(wallet, logger)
notarization_service = NotarizationService(wallet, logger)
secure_message = SecureMessage(wallet)


def convert_account():
    file_encryption_key = wallet.decrypt_from_hex(g.account_data['file_encryption_key'])
    converted_account = dict(g.account_data)
    converted_account['file_encryption_key'] = file_encryption_key
    del converted_account['nonce']
    del converted_account['account_status']
    del converted_account['public_key']
    del converted_account['address']
    return converted_account
from flask import request
from flask_api import FlaskAPI, status

from services.mailgun import MailgunEmailService
from services.pool import PooledEmailService
from services.sendgrid import SendgridEmailService
from email_message import EmailMessage

import logging

app = FlaskAPI(__name__)
pool = PooledEmailService()
logging.basicConfig(level=logging.INFO)


def domain_repr(domain, is_root_admin=False, list_endpoint_urls=False):
    dom = pool.enabled_domains.get(domain)
    if dom is None:
        return None

    out = {"domain": domain, "url": request.host_url + domain}
    if is_root_admin and list_endpoint_urls:
        out["services"] = list(map(lambda x: {
            "name": x.name,
            "priority": x.priority,
            "api_key": x.api_key,
            "url_toggle_failure": "{}{}/{}/fail".format(request.host_url, domain, x.name)
        }, dom['enabled_services']))
    elif is_root_admin:
        out["services"] = list(
            map(lambda x: {"name": x.name, "priority": x.priority, "api_key": x.api_key}, dom['enabled_services']))
Ejemplo n.º 13
0
from bokeh.io import export_png
from datetime import timedelta
import datetime
from bokeh.models import Range1d
import matplotlib.pyplot as plt


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

warnings.simplefilter(action='ignore', category=FutureWarning)

plt.switch_backend('agg')


app = FlaskAPI(__name__)
app.args = {}

api_url = 'https://www.isyatirim.com.tr/_Layouts/15/IsYatirim.Website/Common/ChartData.aspx/IndexHistoricalAll?period=1440&from=%s000000&to=%s235959&endeks=%s.E.BIST'


@app.route('/', methods=['GET'])
def home():
    return render_template('index.html')


@app.route('/stock-names', methods=['GET'])
def stock_names():
    search = request.args.get('search')
    with open(os.path.join('.', 'data', 'stock_names.json')) as f:
        names = json.load(f)
Ejemplo n.º 14
0
def create_app(db_file=None):
    """create app."""
    app = FlaskAPI(__name__)
    per_page = int(
        os.getenv('BUKUSERVER_PER_PAGE', str(views.DEFAULT_PER_PAGE)))
    per_page = per_page if per_page > 0 else views.DEFAULT_PER_PAGE
    app.config['BUKUSERVER_PER_PAGE'] = per_page
    url_render_mode = os.getenv('BUKUSERVER_URL_RENDER_MODE',
                                views.DEFAULT_URL_RENDER_MODE)
    if url_render_mode not in ('full', 'netloc'):
        url_render_mode = views.DEFAULT_URL_RENDER_MODE
    app.config['BUKUSERVER_URL_RENDER_MODE'] = url_render_mode
    app.config['SECRET_KEY'] = os.getenv(
        'BUKUSERVER_SECRET_KEY') or os.urandom(24)
    disable_favicon = os.getenv('BUKUSERVER_DISABLE_FAVICON', 'false')
    app.config['BUKUSERVER_DISABLE_FAVICON'] = \
        False if disable_favicon.lower() in ['false', '0'] else bool(disable_favicon)
    open_in_new_tab = os.getenv('BUKUSERVER_OPEN_IN_NEW_TAB', 'false')
    app.config['BUKUSERVER_OPEN_IN_NEW_TAB'] = \
        False if open_in_new_tab.lower() in ['false', '0'] else bool(open_in_new_tab)
    app.config['BUKUSERVER_DB_FILE'] = os.getenv(
        'BUKUSERVER_DB_FILE') or db_file
    reverse_proxy_path = os.getenv('BUKUSERVER_REVERSE_PROXY_PATH')
    if reverse_proxy_path:
        if not reverse_proxy_path.startswith('/'):
            print('Warning: reverse proxy path should include preceding slash')
        if reverse_proxy_path.endswith('/'):
            print(
                'Warning: reverse proxy path should not include trailing slash'
            )
        app.config['REVERSE_PROXY_PATH'] = reverse_proxy_path
        ReverseProxyPrefixFix(app)
    bukudb = BukuDb(dbfile=app.config['BUKUSERVER_DB_FILE'])
    app.app_context().push()
    setattr(flask.g, 'bukudb', bukudb)

    @app.shell_context_processor
    def shell_context():
        """Shell context definition."""
        return {'app': app, 'bukudb': bukudb}

    app.jinja_env.filters['netloc'] = lambda x: urlparse(x).netloc  # pylint: disable=no-member

    Bootstrap(app)
    admin = Admin(app,
                  name='buku server',
                  template_mode='bootstrap3',
                  index_view=views.CustomAdminIndexView(
                      template='bukuserver/home.html', url='/'))
    # routing
    #  api
    tag_api_view = ApiTagView.as_view('tag_api')
    app.add_url_rule('/api/tags',
                     defaults={'tag': None},
                     view_func=tag_api_view,
                     methods=['GET'])
    app.add_url_rule('/api/tags/<tag>',
                     view_func=tag_api_view,
                     methods=['GET', 'PUT'])
    bookmark_api_view = ApiBookmarkView.as_view('bookmark_api')
    app.add_url_rule('/api/bookmarks',
                     defaults={'rec_id': None},
                     view_func=bookmark_api_view,
                     methods=['GET', 'POST', 'DELETE'])
    app.add_url_rule('/api/bookmarks/<int:rec_id>',
                     view_func=bookmark_api_view,
                     methods=['GET', 'PUT', 'DELETE'])
    app.add_url_rule('/api/bookmarks/refresh',
                     'refresh_bookmark',
                     refresh_bookmark,
                     defaults={'rec_id': None},
                     methods=['POST'])
    app.add_url_rule('/api/bookmarks/<int:rec_id>/refresh',
                     'refresh_bookmark',
                     refresh_bookmark,
                     methods=['POST'])
    app.add_url_rule('/api/bookmarks/<int:rec_id>/tiny',
                     'get_tiny_url',
                     get_tiny_url,
                     methods=['GET'])
    app.add_url_rule('/api/network_handle',
                     'network_handle',
                     handle_network,
                     methods=['POST'])
    bookmark_range_api_view = ApiBookmarkRangeView.as_view(
        'bookmark_range_api')
    app.add_url_rule('/api/bookmarks/<int:starting_id>/<int:ending_id>',
                     view_func=bookmark_range_api_view,
                     methods=['GET', 'PUT', 'DELETE'])
    bookmark_search_api_view = ApiBookmarkSearchView.as_view(
        'bookmark_search_api')
    app.add_url_rule('/api/bookmarks/search',
                     view_func=bookmark_search_api_view,
                     methods=['GET', 'DELETE'])
    #  non api
    admin.add_view(
        views.BookmarkModelView(bukudb,
                                'Bookmarks',
                                page_size=per_page,
                                url_render_mode=url_render_mode))
    admin.add_view(views.TagModelView(bukudb, 'Tags', page_size=per_page))
    admin.add_view(
        views.StatisticView(bukudb, 'Statistic', endpoint='statistic'))
    return app
Ejemplo n.º 15
0
def create_app(config_name):

	bot_id = 'UMTM6Q95F'
	app = FlaskAPI(__name__, instance_relative_config=False)
	app.config.from_object(app_env[config_name])
	app.config.from_pyfile('../config/env.py')
	redis_client = redis.from_url(os.environ.get("REDIS_URL"))

	@app.route('/sendall', methods=['GET'])
	def sendall():
		slackhelper = SlackHelper()
		request = slackhelper.get_users_in_channel()
		if request['ok']:
			for item in request['members']:
				print(item['id'])
				slackhelper.post_message('Morning, where are you located today?\nPlease write your location in one line (city, building, floor...)\nIf you need to search for a user, use his username with the @.\nThank you! :smile:', item['id'])
		
		response_body = {'text': ':)'}
		response = jsonify(response_body)
		response.status_code = 200
		return response

	@app.route('/send', methods=['GET'])
	def send():
		slackhelper = SlackHelper()
		slackhelper.post_message('Morning, where are you located today?\nPlease write your location in one line (city, building, floor...)\nIf you need to search for a user, use his username with the @.\nThank you! :smile:', 'DN036B2PJ')
		response_body = {'text': ':)'}
		response = jsonify(response_body)
		response.status_code = 200
		return response

	@app.route('/clean', methods=['GET'])
	def clean():
		redis_client.flushdb()
		response_body = {'text': ':)'}
		response = jsonify(response_body)
		response.status_code = 200
		return response

	@app.route('/spotbot', methods=['POST'])
	def hackabot():
		command_text = request.data.get('text')
		command_text = command_text.split(' ')
		slack_uid = request.data.get('user_id')
		slackhelper = SlackHelper()
		slack_user_info = slackhelper.user_info(slack_uid)
		actions = Actions(slackhelper, slack_user_info)

		if command_text[0] not in allowed_commands:
			response_body = {'text': 'Invalid Command Sent - `/spotbot info` for available commands'}

		if command_text[0] == 'info':
			response_body = actions.info()

		response = jsonify(response_body)
		response.status_code = 200
		return response

	@app.route('/change', methods=['POST'])
	def change():
		text = request.data.get('text')
		slack_uid = request.data.get('user_id')
		slackhelper = SlackHelper()
		slack_user_info = slackhelper.user_info(slack_uid)
		user_name = slack_user_info['user']['name']
		redis_client.set(user_name.encode('utf8'), text)
		response_body = "Your location is stored succesfully as %s" % (text)
		response = jsonify(response_body)
		response.status_code = 200
		return response

	@app.route('/locate', methods=['POST'])
	def locate():
		text = request.data.get('text')
		text = text.split(' ')
		user = text[0]
		print(user)

		if not user.startswith('@'):
			response_body = {'text': 'The username must start with @'}
		else:
			location = redis_client.get(user[1:]).decode('utf8') or '%s hasn\'t set his location yet' % (user)
			response_body = "%s: %s" % (user, location)

		response = jsonify(response_body)
		response.status_code = 200
		return response

	@app.route('/reaction', methods=['POST'])
	def reaction():
		type = request.data.get('type')
		event = request.data.get('event')
		user_id = event['user']
		channel = event['channel']
		text = event['text']

		if type == 'url_verification':
			response_body = request.data.get('challenge')
		else:
			response_body = 'Hi!'
			if not user_id == bot_id:
				slackhelper = SlackHelper()
				slack_user_info = slackhelper.user_info(user_id)
				user_name = slack_user_info['user']['name']
				clean_user_name = slack_user_info['user']['profile']['real_name_normalized']
				words_to_check = [' close to ',' near ',' next to ',' beside ',' in front of ',' behind ',' on ',' in ',' at ',' on ',' top of ',' within ',' beneath ',' under ','building','bau','basel','kau','kaiseraugst','floor','home','wfh']
				
				print (text)
				if re.search("@(?!\W)", text):
					m = re.findall(r'[@]\w+', text)
					print(m)
					user = m[0]
					print('username: '******'user: '******'user']['profile']['real_name_normalized']
					location = redis_client.get(user[1:]) or 'The user hasn\'t set the location yet'
					if location == 'The user hasn\'t set the location yet':
						slackhelper.post_message(location, channel)
					else:
						slackhelper.post_message("%s:  %s" % (search_clean_user_name, location.decode('utf8')), channel)
				elif any(word.lower() in text.lower() for word in words_to_check):
					slackhelper = SlackHelper()
					print(user_name)
					redis_client.set(user_id, text)
					slackhelper.post_message('Thank you! :smile: I have recorded your location.\nHave a good day!', channel)
				elif 'list' in text:
					if len(redis_client.keys()) > 0:
						list = ''
						print(redis_client.keys())
						for user in redis_client.keys():
							print(user)
							print(slackhelper.user_info(user))
							name =  slackhelper.user_info(user)['user']['profile']['real_name_normalized']
							list = list + name + ': '+ redis_client.get(user).decode('utf8') + '\n'
						slackhelper.post_message(list, user_id)
					else:
						slackhelper.post_message('Sorry, there are no users registered', user_id)

				else:
					slackhelper.post_message('Sorry :disappointed:, I didn\'t understand your request.\n - If you want to add your location, please say in one line where are you located (city, building, floor...)\nIf you need to search for a user use his username with the @.\nThank you! :smile:', channel)

			else:
				print("nothing")
		response = jsonify(response_body)
		response.status_code = 200
		return response

	return app
Ejemplo n.º 16
0
def create_app(config_name):
    app = FlaskAPI(__name__, instance_relative_config=True)

    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config.from_object(app_config[config_name])
    # for removing trailing slashes enforcement
    app.url_map.strict_slashes = False

    db.init_app(app)

    from .models import ExpenseTracker, User

    @app.route('/expenses/', methods=['POST', 'GET'])
    def expense():
        # Get the access token from the header
        auth_header = request.headers.get('Authorization')
        if auth_header is None:
            response = jsonify({
                'message': f'Authorization header missing',
                'status': 'error'
            })
            response.status_code = 401
            return response
        if auth_header == '':
            response = jsonify({
                'message': f'Please insert Bearer token',
                'status': 'error'
            })
            response.status_code = 401
            return response
        access_token = auth_header.split(" ")
        if len(access_token) < 2:
            response = jsonify({
                'message':
                f'Authorization token should start with keyword Bearer',
                'status': 'error'
            })
            response.status_code = 401
            return response
        access_token = auth_header.split(" ")[1]

        if access_token:
            # Attempt to decode the token and get the User ID
            user_id = User.decode_token(access_token)
            if not isinstance(user_id, str):
                # Go ahead and handle the request, the user is authenticated

                if request.method == "POST":
                    name = str(request.data.get('name', ''))
                    amount = str(request.data.get('amount', '')).strip()
                    try:
                        amount_num = float(amount)
                    except ValueError:
                        response = jsonify({
                            'message':
                            f'the amount entered is not a valid number',
                            'status': 'error'
                        })
                        response.status_code = 400
                        return response
                    date_of_expense = str(
                        request.data.get('date_of_expense', '')).strip()
                    try:
                        date = datetime.datetime.strptime(
                            date_of_expense, '%d-%m-%Y')
                    except ValueError:
                        response = jsonify({
                            'message':
                            f'The date {date_of_expense} does not match the format DD-MM-YYYY',
                            'status': 'error'
                        })
                        response.status_code = 400

                        return response

                    if not name:
                        response = jsonify({
                            'message': 'PLease enter a valid name',
                            'status': 'error'
                        })
                        response.status_code = 400

                        return response

                    expense = ExpenseTracker(name=name,
                                             amount=amount_num,
                                             date_of_expense=date,
                                             belongs_to=user_id)
                    expense.save()
                    response = jsonify({
                        'id':
                        expense.id,
                        'name':
                        expense.name,
                        'amount':
                        expense.amount_spent,
                        'date_of_expense':
                        expense.date_of_expense.strftime('%d-%m-%Y'),
                        'date_created':
                        expense.date_created,
                        'date_modified':
                        expense.date_modified,
                        'belongs_to':
                        expense.belongs_to
                    })
                    response.status_code = 201
                    return response

                else:
                    # GET

                    results = []

                    # get the query string for limit if it exists and for pagination
                    # if the query parameter for limit doesn't exist, 20 is used by default

                    limit = request.args.get(
                        'limit', str(Config.DEFAULT_PAGINATION_LIMIT))
                    try:
                        limit = int(limit)
                    except ValueError:
                        # if limit value is gibberish, default to 20
                        limit = Config.DEFAULT_PAGINATION_LIMIT

                    # if limit supplied is greater than 100, display only 100
                    if limit > Config.MAXIMUM_PAGINATION_LIMIT:
                        limit = Config.MAXIMUM_PAGINATION_LIMIT

                    # set the default page to display to 1
                    page = request.args.get('page', '1')

                    try:
                        page = int(page)
                    except ValueError:
                        # if page value is gibberish, default to 1
                        page = 1

                    if limit < 1 or page < 1:
                        return abort(404,
                                     'Page or Limit must be greater than 1')

                    queries = []
                    search_str = request.args.get('name')

                    if search_str:
                        queries.append(
                            ExpenseTracker.name.ilike(f'%{search_str}%'))

                    start_date_str = request.args.get('start_date')

                    if start_date_str:
                        try:
                            start_date = datetime.datetime.strptime(
                                start_date_str, '%d-%m-%Y')
                        except ValueError:
                            response = jsonify({
                                'message':
                                f'The date {start_date_str} does not match the format DD-MM-YYYY',
                                'status': 'error'
                            })
                            response.status_code = 400

                            return response
                        queries.append(
                            ExpenseTracker.date_of_expense >= start_date)

                    end_date_str = request.args.get('end_date')
                    if end_date_str:
                        try:
                            end_date = datetime.datetime.strptime(
                                end_date_str, '%d-%m-%Y')
                        except ValueError:
                            response = jsonify({
                                'message':
                                f'The date {end_date_str} does not match the format DD-MM-YYYY',
                                'status': 'error'
                            })
                            response.status_code = 400

                            return response
                        queries.append(
                            ExpenseTracker.date_of_expense <= end_date)

                    expenses = ExpenseTracker.query.filter_by(
                        belongs_to=user_id).filter(*queries).paginate(
                            page, limit)

                    if page == 1:
                        prev_page = None
                    else:
                        prev_page = url_for(
                            'expense') + f'?limit={limit}&page={page - 1}'

                    if page < expenses.pages:
                        next_page = url_for(
                            'expense') + f'?limit={limit}&page={page + 1}'
                    else:
                        next_page = None

                    for expense in expenses.items:
                        obj = {
                            'id':
                            expense.id,
                            'name':
                            expense.name,
                            'amount':
                            expense.amount_spent,
                            'date_of_expense':
                            expense.date_of_expense.strftime('%d-%m-%Y'),
                            'date_created':
                            expense.date_created,
                            'date_modified':
                            expense.date_modified,
                            'belongs_to':
                            expense.belongs_to
                        }
                        results.append(obj)

                    return make_response(
                        jsonify({
                            'items': results,
                            'total_items': expenses.total,
                            'total_pages': expenses.pages,
                            'prev_page': prev_page,
                            'next_page': next_page,
                        })), 200

            else:
                # user is not legit, so the payload is an error message
                message = user_id
                response = {'message': message}
                return make_response(jsonify(response)), 401
        else:
            response = jsonify({
                'message': f'Please enter an access code',
                'status': 'error'
            })
            response.status_code = 401

            return response

    @app.route('/expenses/<int:id>', methods=['GET', 'PUT', 'DELETE'])
    def expense_manipulation(id, **kwargs):
        auth_header = request.headers.get('Authorization')
        if auth_header is None:
            response = jsonify({
                'message': f'Authorization header missing',
                'status': 'error'
            })
            response.status_code = 401
            return response
        if auth_header == '':
            response = jsonify({
                'message': f'Please insert Bearer token',
                'status': 'error'
            })
            response.status_code = 401
            return response
        access_token = auth_header.split(" ")
        if len(access_token) < 2:
            response = jsonify({
                'message':
                f'Authorization token should start with keyword Bearer',
                'status': 'error'
            })
            response.status_code = 401
            return response
        access_token = auth_header.split(" ")[1]

        if access_token:
            # Get the user id related to this access token
            user_id = User.decode_token(access_token)

            if not isinstance(user_id, str):
                # If the id is not a string(error), we have a user id
                # Get the bucketlist with the id specified from the URL (<int:id>)
                expense = ExpenseTracker.query.filter_by(
                    id=id, belongs_to=user_id).first()

                if not expense:
                    response = jsonify({
                        'message':
                        f'The Expense with this ID: {id} does not exist',
                        'status': 'error'
                    })
                    response.status_code = 404
                    return response
                if request.method == 'DELETE':
                    expense.delete()
                    return {
                        "message":
                        "Expense {} deleted successfully".format(expense.id)
                    }, 200

                elif request.method == 'PUT':
                    name = str(request.data.get('name', ''))
                    amount = str(request.data.get('amount', '')).strip()
                    if amount:
                        try:
                            amount_num = float(amount)
                        except ValueError:
                            response = jsonify({
                                'message':
                                f'the amount entered is not a valid number',
                                'status': 'error'
                            })
                            response.status_code = 400

                            return response
                        expense.amount_spent = amount_num

                    date_of_expense = str(
                        request.data.get('date_of_expense', '')).strip()
                    if date_of_expense:
                        try:
                            date = datetime.datetime.strptime(
                                date_of_expense, '%d-%m-%Y')
                        except ValueError:
                            response = jsonify({
                                'message':
                                f'The date {date_of_expense} does not match the format DD-MM-YYYY',
                                'status': 'error'
                            })
                            response.status_code = 400

                            return response
                        expense.date_of_expense = date
                    if name:
                        expense.name = name
                    else:
                        response = jsonify({
                            'message': 'PLease enter a valid name',
                            'status': 'error'
                        })
                        response.status_code = 400
                        return response

                    expense.save()
                    response = jsonify({
                        'id':
                        expense.id,
                        'name':
                        expense.name,
                        'amount':
                        expense.amount_spent,
                        'date_of_expense':
                        expense.date_of_expense.strftime('%d-%m-%Y'),
                        'date_created':
                        expense.date_created,
                        'date_modified':
                        expense.date_modified,
                        'belongs_to':
                        expense.belongs_to
                    })
                    response.status_code = 200
                    return response

                else:
                    # GET
                    response = jsonify({
                        'id': expense.id,
                        'name': expense.name,
                        'amount': expense.amount_spent,
                        'date_of_expense': expense.date_of_expense,
                        'date_created': expense.date_created,
                        'date_modified': expense.date_modified,
                        'belongs_to': expense.belongs_to
                    })
                    response.status_code = 200
                    return response
        else:
            response = jsonify({
                'message': f'Please enter an access token',
                'status': 'error'
            })
            response.status_code = 401
            return response

    @app.route('/monthly_report', methods=['GET'])
    def month_expense():
        auth_header = request.headers.get('Authorization')
        if auth_header is None:
            response = jsonify({
                'message': f'Authorization header missing',
                'status': 'error'
            })
            response.status_code = 401
            return response
        if auth_header == '':
            response = jsonify({
                'message': f'Please insert Bearer token',
                'status': 'error'
            })
            response.status_code = 401
            return response
        access_token = auth_header.split(" ")
        if len(access_token) < 2:
            response = jsonify({
                'message':
                f'Authorization token should start with keyword Bearer',
                'status': 'error'
            })
            response.status_code = 401
            return response
        access_token = auth_header.split(" ")[1]
        if access_token:
            # Get the user id related to this access token
            user_id = User.decode_token(access_token)

            if not isinstance(user_id, str):
                # If the id is not a string(error), we have a user id
                # Get the bucketlist with the id specified from the URL (<int:id>)
                expenses = ExpenseTracker.query.filter_by(
                    belongs_to=user_id).first()

                month = request.args.get('month')
                if month:
                    try:
                        date = datetime.datetime.strptime(month, '%m-%Y')
                    except ValueError:
                        response = jsonify({
                            'message':
                            f'The date {month} does not match the format MM-YYYY',
                            'status': 'error'
                        })
                        response.status_code = 400

                        return response
                else:
                    response = jsonify({
                        'message': f'Please enter a Month',
                        'status': 'error'
                    })
                    response.status_code = 400

                    return response


                expenses = ExpenseTracker.query.with_entities(
                    func.sum(ExpenseTracker.amount_spent), ExpenseTracker.date_of_expense) \
                    .filter_by(belongs_to=user_id) \
                    .filter(extract('year', ExpenseTracker.date_of_expense) == date.year) \
                    .filter(extract('month', ExpenseTracker.date_of_expense) == date.month) \
                    .group_by(ExpenseTracker.date_of_expense)\
                    .order_by(ExpenseTracker.date_of_expense.desc())\
                    .all()

                #
                # results = dict()
                # for expense in expenses:
                #     expense_date = expense.date_of_expense.strftime('%d/%m/%Y')
                #     if expense_date in results:
                #         results[expense_date] += expense.amount_spent
                #     else:
                #         results[expense_date] = expense.amount_spent
                #
                #
                results = []
                consolidated_total = 0.0
                # expenses.sort(key=lambda tup: tup[1], reverse=True)
                for total_amount, expense_date in expenses:
                    consolidated_total += total_amount
                    obj = {
                        'date': expense_date.strftime('%d/%m/%Y'),
                        'total_expenses': total_amount
                    }
                    results.append(obj)

                return make_response(
                    jsonify({
                        'items': results,
                        'consolidated_total': consolidated_total
                    })), 200
        else:
            response = jsonify({
                'message': f'Please enter an access token',
                'status': 'error'
            })
            response.status_code = 401

            return response

    @app.route('/yearly_report', methods=['GET'])
    def year_expense():
        auth_header = request.headers.get('Authorization')
        if auth_header is None:
            response = jsonify({
                'message': f'Authorization header missing',
                'status': 'error'
            })
            response.status_code = 401
            return response
        if auth_header == '':
            response = jsonify({
                'message': f'Please insert Bearer token',
                'status': 'error'
            })
            response.status_code = 401
            return response
        access_token = auth_header.split(" ")
        if len(access_token) < 2:
            response = jsonify({
                'message':
                f'Authorization token should contain the keyword "Bearer" followed'
                f' by a space and then the access token',
                'status':
                'error'
            })
            response.status_code = 401
            return response
        access_token = auth_header.split(" ")[1]

        if access_token:
            # Get the user id related to this access token
            user_id = User.decode_token(access_token)

            if not isinstance(user_id, str):
                # If the id is not a string(error), we have a user id
                # Get the bucketlist with the id specified from the URL (<int:id>)
                expenses = ExpenseTracker.query.filter_by(
                    belongs_to=user_id).first()

                year = request.args.get('year')
                if year:
                    try:
                        date = datetime.datetime.strptime(year, '%Y')
                    except ValueError:
                        response = jsonify({
                            'message':
                            f'The date {year} does not match the format YYYY',
                            'status': 'error'
                        })
                        response.status_code = 400

                        return response
                else:
                    response = jsonify({
                        'message': f'Please enter a Year',
                        'status': 'error'
                    })
                    response.status_code = 400

                    return response

                expenses = ExpenseTracker.query.with_entities(
                    func.sum(ExpenseTracker.amount_spent).label("total_amount"), extract('month', ExpenseTracker.date_of_expense), extract('year', ExpenseTracker.date_of_expense)) \
                    .filter_by(belongs_to=user_id) \
                    .filter(extract('year', ExpenseTracker.date_of_expense) == date.year) \
                    .group_by(extract('year', ExpenseTracker.date_of_expense), extract('month', ExpenseTracker.date_of_expense)) \
                    .all()

                consolidated_total = 0.0
                results = []
                for total_amount, month, year in expenses:
                    consolidated_total += total_amount
                    obj = {
                        'month': f'{int(month)}-{int(year)}',
                        'total_expenses': total_amount
                    }
                    results.append(obj)

                return make_response(
                    jsonify({
                        'months': results,
                        'consolidated_total': consolidated_total
                    })), 200
        else:
            response = jsonify({
                'message': f'Please enter an access token',
                'status': 'error'
            })
            response.status_code = 401

            return response

    from .auth import auth_blueprint
    app.register_blueprint(auth_blueprint)

    return app
Ejemplo n.º 17
0
# coding: utf-8
from flask import request, url_for
from flask_api import FlaskAPI, status, exceptions
#FlaskAPI docs avilable at http://www.flaskapi.org/
from flask import Flask, render_template
from flask_googlemaps import GoogleMaps
from flask_googlemaps import Map, icons
import json, requests

port = 5000
debug = True
reload = True

app = FlaskAPI(__name__, template_folder="templates")

# you can set key as config
app.config['GOOGLEMAPS_KEY'] = os.environ["GOOGLE_MAPS_API_KEY"]

# you can also pass key here
GoogleMaps(app, key=os.environ["GOOGLE_MAPS_API_KEY"])


#begin Auxiliary Functions
def LLR():
    table = []
    llr_table = []
    count = 0

    with open('MODIS_C6_Global_24h.json', 'r') as data_file:
        for line in data_file:
            try:
Ejemplo n.º 18
0
Description: Initializes the Flask backend object and connectes pyrebase to the backend
by creating a pyrebase instance.
Authors: Imran, Sharan, Nour
"""

####### External imports #######
# import pyrebase for Firebase interaction
import pyrebase

# import supporting flask backend packages
from flask_api import FlaskAPI
from flask.cli import FlaskGroup

# define the Flask backend object and set configuration parameters
app = FlaskAPI(__name__)
app.config["CORS_HEADERS"] = "Content-Type"
cli = FlaskGroup(app)

# initalize a firebase connection to the databse using pyrebase
firebase = pyrebase.initialize_app(
    {
        "apiKey": "AIzaSyDtxf_1m144v64a8gJra4khyQZXnyNYfEk",
        "authDomain": "cse110-bitfit.firebaseapp.com",
        "databaseURL": "https://cse110-bitfit.firebaseio.com",
        "projectId": "cse110-bitfit",
        "storageBucket": "cse110-bitfit.appspot.com",
        "messagingSenderId": "140684277401",
        "appId": "1:140684277401:web:42a04b6e00773d52856a08",
        "measurementId": "G-PHN7BE72HF",
    }
Ejemplo n.º 19
0
import logging
import uuid
from flask import Flask, jsonify, request
from werkzeug.exceptions import HTTPException
from flask_cors import CORS
from flask_api import FlaskAPI
from functools import wraps

log = logging.getLogger(__name__)

#app = Flask(__name__)
app = FlaskAPI(__name__)

# Allows OPTIONS requests everywhere.
cors = CORS(app)

# Default settings
settings = {
    "host": "0.0.0.0",
    "port": 9000,
    "threaded": True,
    # Do not use debug settings here, as this will spawn new processes of the salt-minion
}


@app.errorhandler(Exception)
def handle_error(e):
    log.error('exception occurred: {:}'.format(e))
    code = 500
    if isinstance(e, HTTPException):
        code = e.code
Ejemplo n.º 20
0
from flask import request, url_for
from flask_api import FlaskAPI, status, exceptions
import time

app = FlaskAPI(__name__)


notes = {
    0: 'do the shopping',
    1: 'build the codez',
    2: 'paint the door',
}

def note_repr(key):
    return {
        'url': request.host_url.rstrip('/') + url_for('notes_detail', key=key),
        'text': notes[key]
    }


@app.route("/", methods=['GET', 'POST'])
def notes_list():
    """
    List or create notes.
    """
    if request.method == 'POST':
        note = str(request.data.get('text', ''))
        idx = max(notes.keys()) + 1
        notes[idx] = note
        return note_repr(idx), status.HTTP_201_CREATED
Ejemplo n.º 21
0
from werkzeug.security import safe_str_cmp
from flask_jwt import JWT, jwt_required, current_identity
from peewee import *
from backend.ingredients import getingredients
from .product import containspalm, getname
from backend.carbon import get_carbon_footprint, get_car_footprint
from backend.train import calctrainfromdistance
from backend.plane import calcflightfromdistance
from flask import request
from flask_api import FlaskAPI, status
from playhouse.flask_utils import FlaskDB
from flask_cors import CORS
import datetime
app = FlaskAPI(__name__)
CORS(app)
db_wrapper = FlaskDB(app, 'sqlite:///my_app.db')
from .models import *  # noqa

app.config.from_object(__name__)
app.config["SECRET_KEY"] = "ligma"


def authenticate(username, password):
    user = User.get_or_none(username=username)
    if user is None:
        return None
    if user.verify_password(password):
        return user
    else:
        return None
Ejemplo n.º 22
0
from flask import Response
from flask_api import FlaskAPI
from flask import request
import markdown

from api import OpenPaymentsBL

app = FlaskAPI(__name__)


@app.route("/specialties/", methods=['GET'])
def get_specialties():
    """Returns list of distinct specialties from the data source"""
    specialties = OpenPaymentsBL.OpenPaymentsBL.get_specialties()
    if specialties is None:
        return Response(status=500, response='Error in get specialties')
    return specialties


@app.route("/kol/<string:specialty>", methods=['GET'])
def get_kol(specialty):
    """Returns the top Key opinion leaders for a given specialty
    Arguments:
       :param specialty - the specialty to look for
        limit (optional) - how many rows to return (default = 5)
    """
    if 'limit' in request.args:
        limit = int(request.args['limit'])
        results = OpenPaymentsBL.OpenPaymentsBL.get_kol_by_specialty(specialty, limit)
    else:
        results = OpenPaymentsBL.OpenPaymentsBL.get_kol_by_specialty(specialty)
Ejemplo n.º 23
0
from flask import Flask, Response, request
from flask_api import FlaskAPI, exceptions
from flask_sqlalchemy import SQLAlchemy

import os, datetime, dateparser, iso8601

app = FlaskAPI(__name__)

DB_PATH = os.environ['DB_PATH']
DEFAULT_FROM = os.environ['DEFAULT_FROM']
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.abspath(
    DB_PATH + '/worst-tweets-db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)


class Record(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    key = db.Column(db.String(10))
    timestamp = db.Column(db.DateTime)
    sentiment = db.Column(db.Float)
    text = db.Column(db.String(140))

    def __init__(self, key, timestamp, sentiment, text):
        self.key = key
        self.timestamp = timestamp
        self.sentiment = sentiment
        self.text = text

Ejemplo n.º 24
0
from flask import request, url_for
from flask_api import FlaskAPI, status, exceptions
import tasktiger
from redis import Redis 
from gsoa_task import call_gsoa

# imports GSOA from R
app = FlaskAPI(__name__)
# redis stores all the quque information
conn = Redis(host="redis")
tiger = tasktiger.TaskTiger(connection=conn)
NECESSARY_FIELDS = ['dataFilePath', 'classFilePath', 'gmtFilePath', 'outFilePath']
ACCEPTED_FIELDS = ['classificationAlgorithm', 'numCrossValidationFolds', 'numRandomIterations',
                   'numCores', 'removePercentLowestExpr', 'removePercentLowestVar', 'checkbox'] + NECESSARY_FIELDS


# makes sure the feilds are present 
def validate_input(request_data):
    if set(NECESSARY_FIELDS) - set(request_data.keys()):
        print("necessary fields not added")
    if set(ACCEPTED_FIELDS) - set(request_data.keys()) - set(ACCEPTED_FIELDS):
        print("invalid fields passed : {}".format(set(ACCEPTED_FIELDS) - set(request_data.keys()) - set(ACCEPTED_FIELDS)))
 
   
# puts gsoa jobs into the task tiger queque 
@app.route("/", methods=['GET', 'POST'])
def gsoa_process():
    """
    List or create notes.
    """
Ejemplo n.º 25
0
def create_app(config_name):
    from app.models import Bucketlist, User

    app = FlaskAPI(__name__, instance_relative_config=True)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)

    @app.route('/bucketlists', methods=['POST', 'GET'])
    def bucketlists():
        # Get the access token from the header
        auth_header = request.headers.get('Authorization')
        access_token = auth_header.split(" ")[1]

        if access_token:
            # Attempt to decode the token and get the User ID
            user_id = User.decode_token(access_token)
            if not isinstance(user_id, str):
                # Go ahead and handle the request, the user is authenticated

                if request.method == "POST":
                    name = str(request.data.get('name', ''))
                    if name:
                        bucketlist = Bucketlist(name=name, created_by=user_id)
                        bucketlist.save()
                        response = jsonify({
                            'id': bucketlist.id,
                            'name': bucketlist.name,
                            'date_created': bucketlist.date_created,
                            'date_modified': bucketlist.date_modified,
                            'created_by': user_id
                        })

                        return make_response(response), 201

                else:
                    # GET all the bucketlists created by this user
                    bucketlists = Bucketlist.query.filter_by(
                        created_by=user_id)
                    results = []

                    for bucketlist in bucketlists:
                        obj = {
                            'id': bucketlist.id,
                            'name': bucketlist.name,
                            'date_created': bucketlist.date_created,
                            'date_modified': bucketlist.date_modified,
                            'created_by': bucketlist.created_by
                        }
                        results.append(obj)

                    return make_response(jsonify(results)), 200
            else:
                # user is not legit, so the payload is an error message
                message = user_id
                response = {'message': message}
                return make_response(jsonify(response)), 401

    @app.route('/bucketlists/<int:id>', methods=['GET', 'PUT', 'DELETE'])
    def bucketlist_manipulation(id, **kwargs):

        # Get the access token from the header
        auth_header = request.headers.get('Authorization')
        access_token = auth_header.split(" ")[1]

        if access_token:
            # Attempt to decode the token and get the User ID
            user_id = User.decode_token(access_token)

            if not isinstance(user_id, str):
                # Go ahead and handle the request, the user is authenticated
                # retrieve a buckelist using it's ID
                bucketlist = Bucketlist.query.filter_by(id=id).first()
                if not bucketlist:
                    # Raise an HTTPException with a 404 not found status code
                    abort(404)

                if request.method == 'DELETE':
                    bucketlist.delete()
                    return {
                        "message":
                        "bucketlist {} deleted successfully".format(
                            bucketlist.id)
                    }, 200

                elif request.method == 'PUT':
                    name = str(request.data.get('name', ''))
                    bucketlist.name = name
                    bucketlist.save()
                    response = jsonify({
                        'id':
                        bucketlist.id,
                        'name':
                        bucketlist.name,
                        'date_created':
                        bucketlist.date_created,
                        'date_modified':
                        bucketlist.date_modified
                    })
                    response.status_code = 200
                    return response
                else:
                    # GET
                    response = jsonify({
                        'id':
                        bucketlist.id,
                        'name':
                        bucketlist.name,
                        'date_created':
                        bucketlist.date_created,
                        'date_modified':
                        bucketlist.date_modified
                    })
                    response.status_code = 200
                    return response

            else:
                # user is not legit, so the payload is an error message
                message = user_id
                response = {'message': message}
            return make_response(jsonify(response)), 401

    # import the authentication blueprint and register it on the app
    from .auth import auth_blueprint
    app.register_blueprint(auth_blueprint)

    return app
# from .api.processing_block import BP as PROCESSING_BLOCK
# from .api.processing_block_list import BP as PROCESSING_BLOCK_LIST
# from .api.scheduling_block import BP as SCHEDULING_BLOCK
# from .api.scheduling_block_list import BP as SCHEDULING_BLOCK_LIST


LOG = logging.getLogger('SIP.EC.PCI')
HANDLER = logging.StreamHandler(stream=sys.stdout)
HANDLER.setFormatter(logging.Formatter(
    '%(name)s(%(levelname).6s) %(message)s'))
HANDLER.setLevel(os.getenv('SIP_PCI_LOG_LEVEL', 'WARN'))
LOG.addHandler(HANDLER)
LOG.setLevel(os.getenv('SIP_PCI_LOG_LEVEL', 'WARN'))


APP = FlaskAPI(__name__)
CORS(APP, resources={r"/api/*": {"origins": "*"}})  # needed for the Web GUI?
PREFIX = '/'
APP.register_blueprint(HOME, url_prefix=PREFIX)
APP.register_blueprint(HEALTH, url_prefix=PREFIX)
APP.register_blueprint(SUBARRAY_LIST, url_prefix=PREFIX)
# APP.register_blueprint(SUBARRAY, url_prefix=PREFIX)
# APP.register_blueprint(SCHEDULING_BLOCK_LIST, url_prefix=PREFIX)
# APP.register_blueprint(SCHEDULING_BLOCK, url_prefix=PREFIX)
# APP.register_blueprint(PROCESSING_BLOCK_LIST, url_prefix=PREFIX)
# APP.register_blueprint(PROCESSING_BLOCK, url_prefix=PREFIX)


@APP.route('/')
def home():
    """Temporary helper function to link to the API routes"""
Ejemplo n.º 27
0
def create_app():
    _app = FlaskAPI(__name__)

    return _app
Ejemplo n.º 28
0
from flask import request, url_for
from flask_api import FlaskAPI, status, exceptions
import LED_controller
import time
import json

hostIP = "0.0.0.0"
app = FlaskAPI(__name__)
led = LED_controller.rgb([5, 4, 12])


@app.route("/", methods=['GET', 'POST'])
def get_request():
    if request.method == 'POST':
        return_val = {}
        payload = request.get_json(silent=True)
        if (payload.has_key('rgb')):
            led.set(payload['rgb'])
            print payload['rgb']
            return_val = {'value': 'success'}
        if (payload.has_key('on') and not payload['on']):
            led.set([0, 0, 0])
        return json.dumps(return_val)


if __name__ == "__main__":
    app.run(host=hostIP)
led.end
Ejemplo n.º 29
0
import os

from flask import redirect, request, url_for, jsonify
from flask_api import FlaskAPI, exceptions, status
from werkzeug.utils import secure_filename

import settings
import prediction
import buySuggestion

UPLOAD_FOLDER = os.getenv("UPLOAD_FOLDER")
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

app = FlaskAPI(__name__)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


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


def response(data, uri):
    return {
        'url': uri + url_for('upload_file'),
        'data': {
            'predictions': [float(idx) for idx in data["predictions"]],
            'classes': int(data["classes"]),
            'max_prob': float(data["max_prob"])
        }
Ejemplo n.º 30
0
from flask_api import FlaskAPI
from flask_api import status
from search.util.dataGrabber import grab_and_validate_symbol
from search.service.stockSearch import stock_API_Response

app = FlaskAPI(__name__)


@app.route('/')
def root():
    return ("Welcome to Stock Searcher!<br/>"
            "To search stock please browse:<br/>"
            "https://stock-searcher.appspot.com/Stock_Symbol<br/>"
            "Example: https://stock-searcher.appspot.com/AMZN<br/>"
            "<br/>"
            "To Check status<br/>"
            "https://stock-searcher.appspot.com/status")


@app.route('/<string:stock_symbol>')
def stock_api(stock_symbol):
    return stock_API_Response(stock_symbol)


@app.route('/status')
def status_check():
    if not grab_and_validate_symbol("AMZN"):
        return status.HTTP_404_NOT_FOUND
    return "Server Running"

Ejemplo n.º 31
0
import os
import pandas as pd
from flask import request, url_for, send_from_directory
from flask_api import FlaskAPI, status, exceptions
from werkzeug.utils import secure_filename
from sklearn.preprocessing import normalize
from scipy import stats
import numpy as np
import outliers
import warnings
import datetime
warnings.filterwarnings('ignore')

app = FlaskAPI(__name__)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR,'ddc-api/upload/')
tokenList = pd.read_csv(os.path.join(BASE_DIR,'ddc-api/data/tokens.csv'))

def clean_filename(userid, file_filename):
    now = datetime.datetime.now()
    now_string = now.isoformat().replace(':','-').replace('.','-')
    return now_string + '_' + userid + '_' + secure_filename(file_filename)

def is_jaccard(selected, medication_name):
    tuples = selected[['frequency','dose']].values # sufix _1
    counts = selected[['count']].values

    # Rebuild Original Distribution and Normalization
    hist_freq = []
    hist_dose = []
    pd_hist = pd.DataFrame(columns=['freq','dose'])
Ejemplo n.º 32
0
import os
import sys
# import traceback

from flask_api import FlaskAPI, status
from flask_cors import CORS
from flask_graphql import GraphQLView

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from lib.blame import BlameManager
from lib.graphql.schema import schema

app = FlaskAPI(__name__)
# app.config['DEFAULT_RENDERERS'] = [
#     'flask_api.renderers.JSONRenderer',
#     'flask_api.renderers.BrowsableAPIRenderer',
# ]
CORS(app,
     supports_credentials=True,
     origins=['http://localhost:8080'])

app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=False))

# Optional, for adding batch query support (used in Apollo-Client)
# app.add_url_rule('/graphql/batch', view_func=GraphQLView.as_view('graphql', schema=schema, batch=True))

# TODO: this should probably be an argument to a track-commit or analysis mutation
# excluded_exts = set()
# ext_whitelist = (
#     ".go", ".proto", ".c", ".h", ".sh", ".md", ".xml", ".wixproj", ".wsx", ".cs"
Ejemplo n.º 33
0
from flask_api import FlaskAPI
from settings import config
from controller import ProcessPayment

app = FlaskAPI(__name__)
app.config.from_object(config['development'])

app.add_url_rule(
    '/process-payment',
    view_func=ProcessPayment.as_view('payment_request'),
    methods=['GET', 'POST'],
)

if __name__ == "__main__":
    app.run()
Ejemplo n.º 34
0
def create_app(config_name):
    from app.models import Bucketlist

    app = FlaskAPI(__name__, instance_relative_config=True)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)

    @app.route('/bucketlists/', methods=['POST','GET'])
    def bucketlists():
	if request.method == 'POST':
	    name=str(request.data.get('name', ''))
	    if name:
		bucketlist = Bucketlist(name=name)
		bucketlist.save()
		response = jsonify({
			'id': bucketlist.id,
			'name': bucketlist.date_created,
			'date_created': bucketlist.date_created,
			'date_modiified': bucketlist.date_modified
		})
		response.status_code = 201
		return response
	else:
	    bucketlists = Bucketlist.get_all()
	    results = []
	    for bucketlist in bucketlists:
		obj = {
		'id': bucketlist.id,
		'name': bucketlist.name,
		'date_created': bucketlist.date_created,
		'date_modified':bucketlist.date_modified
		}
	    results.append(obj)
	response = jsonify(results)
	response.status_code = 200
	return response

    @app.route('/bucketlists/<int:id>', methods = ['GET', 'PUT', 'DELETE'])
    def bucketlist_manipulation(id, **kwargs):
	bucketlist = Bucketlist.query.filter_by(id=id).first()
	if not bucketlist:
	    abort(404)
	if request.method == 'DELETE':
	    bucketlist.delete()
	    return {
		"message": "bucketlist {} deleted successfully".format(bucketlist.id)}, 200
	elif request.method == 'PUT':
	    name = str(request.data.get('name', ''))
	    bucketlist.name = name
	    bucketlist.save()
	    response = jsonify({
		'id': bucketlist.id,
		'name': bucketlist.name,
		'date_created': bucketlist.date_created,
		'date_modified': bucketlist.date_modified
		})
	    response.status_code = 200
	    return response
	else:
	    response = jsonify({
		'id': bucketlist.id,
		'name': bucketlist.name,
		'date_created': bucketlist.date_created,
		'date_modified': bucketlist.date_modified
		})
	    response.status_code = 200
	    return response


    return app
Ejemplo n.º 35
0
def create_app(config_name):

    app = FlaskAPI(__name__, instance_relative_config=True)
    # overriding Werkzeugs built-in password hashing utilities using Bcrypt.
    bcrypt = Bcrypt(app)

    app.config.from_object(app_config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)

    @app.route('/api/real/login/account', methods=['POST'])
    def login():

        password = request.data.get('password', '')
        userName = request.data.get('userName', '')

        user = User.get_all().filter(User.userName == userName).first()

        if user is not None:
            response = jsonify({
                'status': 'ok',
                'type': 'account',
                'userId': user.id,
                'currentAuthority': 'admin'
            })
            loggedinuser = user.id
            session = Session(user.id)
            session.save()

            print('saved')
            return make_response(response), 200

        return make_response(
            jsonify({
                'status': 'error',
                'type': 'account',
                'currentAuthority': 'guest'
            })), 200

    @app.route('/api/real/logout', methods=['POST'])
    def logout():
        Session.delete_all()
        return make_response(jsonify({'status': 'ok'})), 200

    @app.route('/api/real/currentUser', methods=['GET'])
    def currentUser():

        session = Session.get_all().first()

        if session == None:
            return make_response(
                jsonify({
                    'status': 'ok',
                    'type': 'account',
                    'currentAuthority': 'guest'
                })), 200

        print(session.userId)
        user = User.get_all().filter(User.id == session.userId).first()

        res = user.serialise()

        res['favourites'] = []
        #for fav in user.favourites:
        # res['favourites'].append(Card.get_all().filter(Card.id == fav.cardId).first().serialise())

        response = jsonify(res)
        return make_response(response), 200

    @app.route('/api/real/pages', methods=['GET'])
    def getPages():

        pages = Page.query.filter(Page.url == "dashboard/crossfiltermap")

        results = []
        for page in pages:
            results.append(page.serialise())

        return make_response(jsonify({'list': results})), 200

    @app.route('/api/real/cardpositions', methods=['GET', 'POST'])
    def getCardPositions():
        url = request.data.get('url', "/dashboard/analysis")
        userId = request.data.get('userId', 0)
        problemsetId = request.data.get('problemset', 0)

        position = request.data.get('position', None)

        page = Page.query.filter(Page.url == url).first()

        records = CardPosition.query.filter(
            CardPosition.key["id"].astext == str(problemsetId)).all()

        print(records)

        #get all cards for this page, with optional position parameter
        if position == None:
            cardpositions = CardPosition.query.filter(
                CardPosition.userId == userId).filter(
                    CardPosition.key["type"].astext == "problemset").filter(
                        CardPosition.key["id"].astext == str(problemsetId))
        else:
            cardpositions = CardPosition.query.filter(
                CardPosition.userId ==
                userId).filter(CardPosition.position == position).filter(
                    CardPosition.key["type"].astext == "problemset").filter(
                        CardPosition.key["id"].astext == str(problemsetId))

        results = []
        for cardposition in cardpositions.all():
            results.append(cardposition.serialise())

        return make_response(jsonify({'list': results})), 200

    @app.route('/api/real/cardpositions/new', methods=['POST'])
    def newCardPositions():

        cardId = request.data.get('cardId', 0)
        position = request.data.get('position', 0)
        key = request.data.get('key', {})

        cardposition = CardPosition(1, cardId, 1, 4, position, key)
        cardposition.save()

        return make_response(jsonify(cardposition.serialise())), 200

    @app.route('/api/real/favourites', methods=['GET'])
    def getFavourites():

        favs = Favourite.query.all()

        results = []
        for fav in favs:
            results.append(page.serialise())

        return make_response(jsonify({'list': results})), 200

    @app.route('/api/real/favourites', methods=['POST'])
    def create_fav():

        userId = request.data.get('userId', 0)
        cardId = request.data.get('cardId', 0)

        fav = Favourite(userId, cardId)
        fav.save()

        favs = Favourite.get_all().all()

        results = []
        for fav in favs:
            results.append(fav.serialise())

        return make_response(jsonify({'list': results})), 200

    @app.route('/api/real/admin/cardmappings', methods=['POST'])
    def list_cardmappings():

        url = request.data.get('url', '')
        userId = request.data.get('userId', 0)
        page = Page.get_all().filter(Page.url == url).one()

        mappings = PageCard.get_all().filter(
            PageCard.pageId == page.id).filter(
                PageCard.userId == userId).order_by(PageCard.id).all()

        results = []
        for mapping in mappings:
            results.append(mapping.serialise())

        return make_response(jsonify({'list': results})), 200

    @app.route('/api/real/admin/cardmappings/<id>', methods=['POST'])
    def update_cardmapping(id):

        enabled = request.data.get('enabled', 'N')
        url = request.data.get('url', '')
        userId = request.data.get('userId', 0)

        mapping = PageCard.get_all().filter(PageCard.id == id).one()
        mapping.enabled = enabled
        mapping.save()

        page = Page.get_all().filter(Page.url == url).one()
        mappings = PageCard.get_all().filter(PageCard.userId == userId).filter(
            PageCard.pageId == page.id).order_by(PageCard.id).all()

        results = []
        for mapping in mappings:
            results.append(mapping.serialise())

        return make_response(jsonify({'list': results})), 200

    @app.route('/api/real/cards', methods=['POST'])
    def list_cards():

        userid = request.data.get('userid', '0')
        url = request.data.get('url', '')
        type = request.data.get('type', '')
        id = str(request.data.get('id', ''))

        sql = text('select id from cards where key->> \'type\' = \'' + type +
                   '\' and key->>\'id\' = \'' + id + '\'')
        print(sql)
        result = db.engine.execute(sql)

        cardids = []
        for row in result:
            cardids.append(row[0])

        cards = Card.get_all().filter(Card.id.in_(cardids)).all()

        results = []
        for card in cards:
            results.append(card.serialise())

        return make_response(jsonify({'list': results})), 200

    @app.route('/api/real/cards/new', methods=['POST'])
    def new_card():

        card = Card(request.data.get('component'), request.data.get('key', {}),
                    request.data.get('data', {}))
        card.save()

        import time
        time.sleep(1)

        return make_response(jsonify(card.serialise())), 200

    @app.route('/api/real/cards/save', methods=['POST'])
    def save_card():

        id = str(request.data.get('id', ''))
        card = Card.get_all().filter(Card.id == id).one()
        card.data = request.data.get('data', {})
        card.save()

        results = []

        return make_response(jsonify({'list': results})), 200

    @app.route('/api/real/cards/<id>', methods=['GET'])
    def get_card(id):

        cards = Card.get_all().filter(Card.id == id).all()

        results = []
        for card in cards:
            results.append(card.serialise())

        return make_response(jsonify({'list': results})), 200

    @app.route('/api/real/favourites/clear', methods=['POST'])
    def clearfav():
        userid = request.data.get('userId', '0')
        Favourite.delete_all(userid)
        return make_response(jsonify({'status': 'ok'})), 200

    @app.route('/api/real/imports/countries', methods=['GET'])
    def import_countries():

        with urllib.request.urlopen(
                "https://raw.githubusercontent.com/iancoleman/cia_world_factbook_api/master/data/2018-05-28_factbook.json"
        ) as url:
            data = json.loads(url.read().decode())

            for country in data['countries']:
                country = Country(data['countries'][country]['data'], {})
                country.save()
                #print (data['countries'][country]['data']['name'])

            return make_response(jsonify({'status': 'imported'})), 200

    return app
Ejemplo n.º 36
0
def create_app(config_filename=None):
    """create app."""
    app = FlaskAPI(__name__)
    per_page = int(os.getenv('BUKUSERVER_PER_PAGE', str(views.DEFAULT_PER_PAGE)))
    per_page = per_page if per_page > 0 else views.DEFAULT_PER_PAGE
    app.config['BUKUSERVER_PER_PAGE'] = per_page
    url_render_mode = os.getenv('BUKUSERVER_URL_RENDER_MODE', views.DEFAULT_URL_RENDER_MODE)
    if url_render_mode not in ('full', 'netloc'):
        url_render_mode = views.DEFAULT_URL_RENDER_MODE
    app.config['BUKUSERVER_URL_RENDER_MODE'] = url_render_mode
    app.config['SECRET_KEY'] = os.getenv('BUKUSERVER_SECRET_KEY') or os.urandom(24)
    bukudb = BukuDb()
    app.app_context().push()
    setattr(flask.g, 'bukudb', bukudb)

    @app.shell_context_processor
    def shell_context():
        """Shell context definition."""
        return {'app': app, 'bukudb': bukudb}

    app.jinja_env.filters['netloc'] = lambda x: urlparse(x).netloc  # pylint: disable=no-member

    Bootstrap(app)
    admin = Admin(
        app, name='Buku Server', template_mode='bootstrap3',
        index_view=views.CustomAdminIndexView(
            template='bukuserver/home.html', url='/'
        )
    )
    # routing
    #  api
    app.add_url_rule('/api/tags', 'get_tags', tag_list, methods=['GET'])
    app.add_url_rule('/api/tags/<tag>', 'update_tag', tag_detail, methods=['GET', 'PUT'])
    app.add_url_rule('/api/network_handle', 'networkk_handle', network_handle_detail, methods=['POST'])
    app.add_url_rule('/api/bookmarks', 'bookmarks', bookmarks, methods=['GET', 'POST', 'DELETE'])
    app.add_url_rule('/api/bookmarks/refresh', 'refresh_bookmarks', refresh_bookmarks, methods=['POST'])
    app.add_url_rule('/api/bookmarks/<id>', 'bookmark_api', bookmark_api, methods=['GET', 'PUT', 'DELETE'])
    app.add_url_rule('/api/bookmarks/<id>/refresh', 'refresh_bookmark', refresh_bookmark, methods=['POST'])
    app.add_url_rule('/api/bookmarks/<id>/tiny', 'get_tiny_url', get_tiny_url, methods=['GET'])
    app.add_url_rule('/api/bookmarks/<id>/long', 'get_long_url', get_long_url, methods=['GET'])
    app.add_url_rule(
        '/api/bookmarks/<starting_id>/<ending_id>',
        'bookmark_range_operations', bookmark_range_operations, methods=['GET', 'PUT', 'DELETE'])
    app.add_url_rule('/api/bookmarks/search', 'search_bookmarks', search_bookmarks, methods=['GET', 'DELETE'])
    #  non api
    admin.add_view(views.BookmarkModelView(
        bukudb, 'Bookmarks', page_size=per_page, url_render_mode=url_render_mode))
    admin.add_view(views.TagModelView(
        bukudb, 'Tags', page_size=per_page))
    admin.add_view(views.StatisticView('Statistic', endpoint='statistic'))
    return app
Ejemplo n.º 37
0
from flask_api import FlaskAPI
from flask_sqlalchemy import SQLAlchemy

app = FlaskAPI(__name__)
app.config[
    "SQLALCHEMY_DATABASE_URI"] = "mysql://*****:*****@localhost/toko_online"

db = SQLAlchemy(app)

from . import route
Ejemplo n.º 38
0
#from pymongo import MongoClient
import pymongo
from bson import Binary, Code
from bson.json_util import dumps
from bson.objectid import ObjectId

import datetime

import json
import urllib


import timeit

app = FlaskAPI(__name__)
CORS(app)

client = pymongo.MongoClient('localhost', 27017)
db = client['5303DB']
businessdb = db['yelp.business']
review = db['yelp.review']
userdb = db['yelp.user']


parser = reqparse.RequestParser()

"""=================================================================================="""
"""=================================================================================="""
"""=================================================================================="""
Ejemplo n.º 39
0
def create_app(config_name):

    from app.models import Item, Bid, User

    app = FlaskAPI(__name__, instance_relative_config=True)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)

    @app.route('/')
    def index():
        return 'Auction API'

    @app.route('/items/all', methods=['GET'])
    def items_all():
        items = Item.get_all()
        results = []
        for item in items:
            obj = {
                'id': item.item_id,
                'name': item.name,
                'description': item.description,
                'start_time': item.start_time,
                'end_time': item.end_time,
                'start_amount': item.start_amount
            }
            results.append(obj)
        response = jsonify(results)
        response.status_code = 200
        return response

    @app.route('/items/upcoming', methods=['GET'])
    def items_upcoming():
        current_time = str(datetime.now())
        items = Item.query.filter(current_time < Item.start_time).all()
        results = []
        for item in items:
            obj = {
                'id': item.item_id,
                'name': item.name,
                'description': item.description,
                'start_time': item.start_time,
                'end_time': item.end_time,
                'start_amount': item.start_amount
            }
            results.append(obj)
        response = jsonify(results)
        response.status_code = 200
        return response

    @app.route('/items/previous', methods=['GET'])
    def items_previous():
        current_time = str(datetime.now())
        items = Item.query.filter(current_time > Item.end_time).all()
        results = []
        for item in items:
            obj = {
                'id': item.item_id,
                'name': item.name,
                'description': item.description,
                'start_time': item.start_time,
                'end_time': item.end_time,
                'start_amount': item.start_amount
            }
            results.append(obj)
        response = jsonify(results)
        response.status_code = 200
        return response

    @app.route('/item/<int:id>', methods=['GET'])
    def item_details(id):
        result = []
        current_time = str(datetime.now())
        #For previous auctions
        item = Item.query.filter(
            and_(Item.item_id == id, current_time > Item.end_time)).first()
        if item is not None:
            obj = {
                'id': item.item_id,
                'name': item.name,
                'buyer': '<winner_name>',
                'amount': '<highest_bid>',
                'status': 'auction complete'
            }
            #For ongoing auctions
        else:
            item = Item.query.filter(
                and_(Item.item_id == id, current_time > Item.start_time,
                     current_time < Item.end_time)).first()
            if item is not None:
                obj = {
                    'id': item.item_id,
                    'name': item.name,
                    'highest_bid': '<highest_bid>',
                    'status': 'auction ongoing'
                }
            else:
                obj = {'status': 'auction has not been started yet'}
        result.append(obj)
        response = jsonify(result)
        response.status_code = 200
        return response

    @app.route('/bids/user/<int:id>', methods=['GET'])
    def bids_by_user(id):
        result = []
        user = User.query.get(id)
        #If user_id doesn't exist
        if not user:
            obj = {'message': 'User not registered'}
            result.append(obj)
            response = jsonify(result)
            response.status_code = 404
            return response

        bids = Bid.query.filter_by(placed_by=user.user_id).all()
        #If no bid by current user
        if not bids:
            obj = {'message': 'No bids placed by this User'}
            result.append(obj)
            response = jsonify(result)
            response.status_code = 404
            return response

        #Display bids by user and item names
        for bid in bids:
            item = Item.query.get(bid.bid_on_item)
            obj = {
                'bid_id': bid.bid_id,
                'bid_price': bid.bid_amount,
                'item_name': item.name
            }
            result.append(obj)
        response = jsonify(result)
        response.status_code = 200
        return response

    @app.route('/item/bid', methods=['POST'])
    def bid_on_item():
        """Check whether user is logged in or not"""
        auth_header = request.headers.get('Authorization')
        access_token = auth_header.split(" ")[1]

        if access_token:
            #Attempt to decode the token and get the user_id
            user_id = User.decode_token(access_token)
            if not isinstance(user_id, str):
                #User is authenticated

                if request.method == 'POST':
                    bid_amount = float(request.data.get('bid_amount', ''))
                    bid_on_item = int(request.data.get('bid_on_item', ''))
                    if bid_amount and bid_on_item:
                        placed_bid = Bid(placed_by=user_id,
                                         bid_amount=bid_amount,
                                         bid_on_item=bid_on_item)
                        placed_bid.save()
                        item = Item.query.filter_by(
                            item_id=placed_bid.bid_on_item).first()
                        response = jsonify({
                            'status': 'bid successfully placed',
                            'bid_id': placed_bid.bid_id,
                            'bid_amount': placed_bid.bid_amount,
                            'placed_on': item.name,
                        })
                        return make_response(response), 201
                else:
                    response = jsonify({
                        'status':
                        'send a POST request with bid_amount and bid_on_item as form data to place bid'
                    })
                    return make_response(response), 200
            else:
                #User is not legit
                message = user_id
                response = {'message': message}
                return make_response(jsonify(response)), 401

    #Register auth blueprint
    from .auth import auth_blueprint
    app.register_blueprint(auth_blueprint)

    return app
Ejemplo n.º 40
0
from flask_api import FlaskAPI
import random

app = FlaskAPI(__name__)

kelimeler =[]
with open('static/kelimeler.txt',encoding='utf-8') as fd:
    for kelime in fd:
        kelimeler.append(kelime.strip())

def get_random_kelime(say):
    if say is None: n = 1
    else: n = say
    if n<1: n = 1
    elif n>10: n = 10

    sayilar = []
    for m in range(n):
        sayilar.append(random.randrange(len(kelimeler)))

    kelimelist=[]
    for m in range(n):
        kelimelist.append(kelimeler[sayilar[m]])
    return kelimelist
        
def kelime_yolla():
    return {
	'sayı': 0,
        'text': get_random_kelime(1)[0]
    }
Ejemplo n.º 41
0
def _run():
    app = FlaskAPI(__name__)
    app.url_map.converters['regex'] = RegexConverter
    app.debug = True
    app.register_blueprint(api, url_prefix=DEFAULT_PREFIX)
    app.run("0.0.0.0")
Ejemplo n.º 42
0
# coding: utf8
from __future__ import unicode_literals
from flask import abort, make_response, request
from flask_api.decorators import set_renderers
from flask_api import exceptions, renderers, status, FlaskAPI
import json
import unittest


app = FlaskAPI(__name__)
app.config['TESTING'] = True


class JSONVersion1(renderers.JSONRenderer):
    media_type = 'application/json; api-version="1.0"'


class JSONVersion2(renderers.JSONRenderer):
    media_type = 'application/json; api-version="2.0"'


@app.route('/set_status_and_headers/')
def set_status_and_headers():
    headers = {'Location': 'http://example.com/456'}
    return {'example': 'content'}, status.HTTP_201_CREATED, headers


@app.route('/set_headers/')
def set_headers():
    headers = {'Location': 'http://example.com/456'}
    return {'example': 'content'}, headers
Ejemplo n.º 43
0
VERSION = (0, 2, 0)
version = ".".join(map(str, VERSION))

from . import focus, lights, telescope
from .utils import RegexConverter, BrowsableAPITitleRenderer


MODULES = (
    lights,
    focus,
    telescope,
)


app = FlaskAPI(__name__)
app.debug = False
app.url_map.converters['regex'] = RegexConverter

for module in MODULES:
    app.register_blueprint(module.api, url_prefix=module.DEFAULT_PREFIX)


@set_renderers(BrowsableAPITitleRenderer, JSONRenderer)
def dagor_api():
    """
    API root

    version: {VERSION}

    ### Hyperlinks
Ejemplo n.º 44
0
from flask_api import FlaskAPI

app = FlaskAPI(__name__)


@app.route('/example/')
def example():
    return {'hello': 'world'}

if __name__ == "__main__":
    app.run(debug=True)
Ejemplo n.º 45
0
from flask_api import FlaskAPI
from flask import request
import json
app = FlaskAPI(__name__)


@app.route('/get_word_count/', methods=['GET', 'POST'])
def get_word_count():
    print(request)
    if request.method == 'GET':
        return 'Invalid Request'

    if request.method == 'POST':
        data = request.get_json()
        output = {}
        if not data:
            output = {'message': 'No Text Received'}
            return output
        for key in data.keys():
            text = data[key]
            text = text.split(' ')
            output[key] = {}
            for word in text:
                if word not in output[key]:
                    output[key][word] = 1
                else:
                    output[key][word] += 1
        return output


if __name__ == '__main__':
Ejemplo n.º 46
0
# coding: utf8
from __future__ import unicode_literals
from flask import abort, make_response, request
from flask_api.decorators import set_renderers
from flask_api import exceptions, renderers, status, FlaskAPI
import json
import unittest


app = FlaskAPI(__name__)
app.config["TESTING"] = True


class JSONVersion1(renderers.JSONRenderer):
    media_type = 'application/json; api-version="1.0"'


class JSONVersion2(renderers.JSONRenderer):
    media_type = 'application/json; api-version="2.0"'


@app.route("/set_status_and_headers/")
def set_status_and_headers():
    headers = {"Location": "http://example.com/456"}
    return {"example": "content"}, status.HTTP_201_CREATED, headers


@app.route("/set_headers/")
def set_headers():
    headers = {"Location": "http://example.com/456"}
    return {"example": "content"}, headers
Ejemplo n.º 47
0
from flask_api import FlaskAPI
from flask_sqlalchemy import SQLAlchemy

app = FlaskAPI(__name__)

# SQLALCHEMY_DATABASE_URI = 'sqlite:///dev.db'
# RUN_CONFIG = {
#     'host': '127.0.0.1',
#     'port': 5000,
#     'debug': True,
# }

try:
    from config import *
except Exception as e:
    print('not found config file')
finally:
    app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

    DB = SQLAlchemy(app)
    # SESSION = SignallingSession(DB)
    # session = SESSION()

app.config['DEFAULT_RENDERERS'] = [
    'flask.ext.api.renderers.JSONRenderer',
    'flask.ext.api.renderers.BrowsableAPIRenderer',
]
Ejemplo n.º 48
0
def create_app(config_name):
    from app.models import Users, Location, Restaurant, Category
    app = FlaskAPI(__name__, instance_relative_config=True)
    CORS(app)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)

    def token_required(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            if 'x-access-token' in request.headers:
                token = request.headers['x-access-token']

            if not token:
                return jsonify({'message': 'Access Token not available', 'status': False})

            try:
                data = jwt.decode(token, os.getenv('SECRET'))
                current_user = Users.query.filter_by(email=data['email']).first()
            except:
                return jsonify({'message': 'Invalid token', 'status': False})
            return f(current_user, *args, **kwargs)
        return decorated

    @app.route('/auth/register', methods=['POST'])
    def register():
        data = request.data.get('email')
        print(data)

        email = request.data.get('email')
        name = request.data.get('name')
        password = request.data.get('password')


        if email.isspace() or name.isspace() or password.isspace():
            response = jsonify({
                'message': 'all fields are required',
                'status': False
            })
            response.status_code = 401
            return response
        else:            
            hashed_password = generate_password_hash(password, method='sha256')
            new_user = Users(email=email, name=name, role='customer', password=hashed_password)
            new_user.save()

            response = jsonify({
                'id': new_user.id,
                'email': new_user.email,
                'name': new_user.name,
                'role': new_user.role
            })
            response.status_code = 201
            return response
        

    @app.route('/auth/login', methods=['POST'])
    def login():
        email = str(request.data.get('email'))
        password = str(request.data.get('password'))

        user = Users.query.filter_by(email=email).first()
        
        if user:
            if check_password_hash(user.password, password):
                token = jwt.encode({'email': user.email, 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=90)}, os.getenv('SECRET'))
                response = jsonify({
                    'message': 'successfully logged in',
                    'status': True,
                    'token': token.decode('UTF-8')
                })
                response.status_code = 200
                return response
            else:
                response = jsonify({
                    'message': 'password is incorrect',
                    'status': False
                })

                response.status_code = 401
                return response
        else:
            response = jsonify({
                'message': 'user not found',
                'status': False
            })
            response.status_code = 401
            return response
    

    @app.route('/users', methods=['GET'])
    def users():
        users = Users.query.all()
        results = []

        for user in users:
            obj = {
                'id': user.id,
                'name': user.name,
                'email': user.email,
                'role': user.role,
                'date_created': user.date_created,
                'date_modified': user.date_modified
            }

            results.append(obj)

        response = jsonify(results)
        response.status_code = 200

        return response

    @app.route('/users/<int:id>', methods=['GET'])
    def get_user(id):
        user = Users.query.filter_by(id=id).first()

        if not user:
            abort(404)

        response = jsonify({
            'id': user.id,
            'name': user.name,
            'email':user.email,
            'role': user.role,
            'date_created': user.date_created,
            'date_modified': user.date_modified
        })
        response.status_code = 200
        return response

    @app.route('/users/<int:id>', methods=['PUT'])
    def edit_user(id):
        user = Users.query.filter_by(id=id).first()

        if not user:
            abort(404)
        user.name = str(request.data.get('name'))
        user.email = str(request.data.get('email'))
        user.role = str(request.data.get('role'))

        user.save()
        response = jsonify({
            'id': user.id,
            'name': str(request.data.get('name')),
            'msg': 'Update successful'
        })
        response.status_code = 200

        return response

    @app.route('/location', methods=['POST'])
    @token_required
    def location(current_user):
        county = str(request.data.get('county'))
        location = str(request.data.get('location'))

        user_location = Location(current_user.id, county, location)
        user_location.save()

        response = jsonify({
            'message': 'Successfully added user location',
            'status': True
        })
        response.status_code = 201
        return response

    @app.route('/restaurant', methods=['POST'])
    @token_required
    def restaurant(current_user):
        if current_user.role != 'admin':
            response = jsonify({
                'message': 'Unauthorized command',
                'status': False
            })
            response.status_code = 401

            return response

        restaurant_name = str(request.data.get('restaurant_name'))
        restaurant_email = str(request.data.get('restaurant_email'))
        restaurant_county = str(request.data.get('restaurant_county'))
        restaurant_location = str(request.data.get('restaurant_location'))
        restaurant_minorder = str(request.data.get('restaurant_minorder'))
        restaurant_phone = str(request.data.get('restaurant_phone'))
        restaurant_mobile = str(request.data.get('restaurant_mobile'))
        restaurant_about = str(request.data.get('restaurant_about'))
        restaurant_delivery = str(request.data.get('restaurant_delivery'))

        if restaurant_name.isspace() or restaurant_email.isspace() or restaurant_county.isspace() or restaurant_location.isspace():
            response = jsonify({
                'message': 'All fields are required',
                'status': False
            })

            return response
        elif restaurant_minorder.isspace() or restaurant_phone.isspace() or restaurant_mobile.isspace():
            reponse = jsonify({
                'message': 'All fields are required',
                'status': False
            })

            return response
        elif restaurant_about.isspace() or restaurant_delivery.isspace():
            response = jsonify({
                'message': 'All fields are required',
                'status': False
            })

            return response
        else: 
            new_restaurant = Restaurant(restaurant_name, restaurant_email, restaurant_county, restaurant_location, restaurant_minorder, restaurant_phone, restaurant_mobile, restaurant_about, restaurant_delivery)
            new_restaurant.save()

            response = jsonify({
                'Message': 'Successfully added new Restaurant',
                'Status': True
            })

            response.status_code = 201
            return response


    @app.route('/restaurant/category', methods=['POST'])
    @token_required
    def add_category(current_user):
        if current_user.role != 'admin':
            response = jsonify({
                'message': 'You don\'t have the right permission',
                'status': False
            })
            response.status_code = 401

            return response

        new_category = Category(request.data.get('restaurant_id'), request.data.get('category_name'))
        new_category.save()

        response = jsonify({
            'message': 'Successfully added new category',
            'status': True
        })
        response.status_code = 201

        return response

    @app.route('/restaurant/categories/<int:id>', methods=['GET'])
    @token_required
    def get_categories(current_user, id):
        """Gets the list of categories by restaurant_id."""
        categories = []

        cats = Category.query.filter_by(restaurant_id=id).all()
        for cat in cats:
            category = {
                'id': cat.id,
                'name': cat.name,
                'restaurant': cat.restaurant_id
            }
            categories.append(category)

        response = jsonify({
            'status': True,
            'categories': categories
        })

        response.status_code = 200
        return response

    @app.route('/restaurant/category/<int:id>', methods=['PUT'])
    @token_required
    def edit_category(current_user, id):
        """Edits the restaurants menu category."""
        restaurant_category = Category.query.filter_by(id=id).first()
        if not restaurant_category:
            return jsonify({'message': 'Category not found', 'status': False})
        restaurant_category.name = str(request.data.get('category_name'))
        db.session.commit()

    @app.route('/restaurant/category/<int:id>', methods=['DELETE'])
    @token_required
    def delete_category(current_user, id):
        """Deletes the category by id."""
        restaurant_category = Category.query.filter_by(id=id).first()
        if not restaurant_category:
            return jsonify({'message': 'category not found', 'status': False})
        db.session.delete(restaurant_category)
        db.session.commit()

        return jsonify({'message': 'Category has been successfully deleted', 'status': True})
        

    return app
Ejemplo n.º 49
0
def create_app(config_name):
    from app.models import Happycal
    app = FlaskAPI(__name__, instance_relative_config=True)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    db.init_app(app)

    @app.route('/happycals/', methods=['POST', 'GET'])
    def happycals():
        if request.method == "POST":
            name = str(request.data.get('name',''))
            if name:
                happycal = Happycal(name=name)
                happycal.save()
                response = jsonify({
                    'id':happycal.id,
                    'name':happycal.name,
                    'date_created':happycal.date_created,
                    'date_modified':happycal.date_modified
                })
                response.status_code = 201
                return response
        else:
            #GET
            happycals = Happycal.get_all()
            results = []

            for happycal in happycals : 
                obj = {
                    'id':happycal.id,
                    'name':happycal.name,
                    'date_created':happycal.date_created,
                    'date_modified':happycal.date_modified
                }
                results.append(obj)
            response = jsonify(results)
            response.status_code = 200
            return response
    @app.route('/happycals/<int:id>', methods=['GET','PUT','DELETE'])
    def happycal_manipulation(id, **kwargs):
        #retrieve a bucketlist using its ID
        happycal = Happycal.query.filter_by(id=id).first()
        if not happycal:
            #Raise a 404 not found status code
            abort(404)
        if request.method == 'DELETE':
            happycal.delete()
            return {"message":"happycal {} deleted successfully".format(happycal.id)},200

        elif request.method =='PUT':
            name = str(request.data.get('name',''))
            happycal.name = name
            happycal.save()
            response = jsonify({
                'id':happycal.id,
                'name':happycal.name,
                'date_created':happycal.date_created,
                'date_modified':happycal.date_modified
            })
            response.status_code = 200
            return response

        else: 
            #GET
            response = jsonify({
                'id':happycal.id,
                'name':happycal.name,
                'date_created':happycal.date_created,
                'date_modified':happycal.date_modified
            })
            response.status_code=200
            return response

    return app
Ejemplo n.º 50
0
from flask import request, url_for, jsonify
from flask_api import FlaskAPI, status, exceptions
from flask_cors import CORS, cross_origin
from bs4 import BeautifulSoup
import PyPDF2
from summarize import summarize
import requests
import pdfx

app = FlaskAPI(__name__)
CORS(app)

###################### FLASK APIs ###############################################


class InvalidUsage(Exception):
    def __init__(self, message):
        super(InvalidUsage, self).__init__()
        self.message = message


@app.route("/sampleGetRequest", methods=['GET'])
def get_request():

    if request.method == 'GET':
        sample_data = request.args.get('data')

        modified_data = sample_data + " modify kar diya."

        resp = {"modified_data": modified_data}
Ejemplo n.º 51
0
    headers['X-RateLimit-Reset'] = '0'
    headers['X-Poll-Interval'] = '0'

    headers['X-Frame-Options'] = 'deny'
    headers['X-Content-Type-Options'] = 'nosniff'
    headers['X-Xss-Protection'] = '1; mode=block'
    headers['Content-Security-Policy'] = "default-src 'self'"
    headers['access-control-allow-origin'] = '*'
    headers['strict-transport-security'] = 'max-age=31536000; includeSubdomains; preload'

    headers['access-control-expose-headers'] = 'X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-Poll-Interval'

    return output , code , headers


app = FlaskAPI(__name__)

app.config['DEFAULT_RENDERERS'] = [
    'flask_api.renderers.JSONRenderer',
    'flask_api.renderers.BrowsableAPIRenderer',
]

@app.route("/")
def app_route_root():
    root = request.host_url.rstrip('/')
    return postprocess( {
        'url' : root + url_for( 'app_route_root' ) ,
        'links' : {
            'network' : root + url_for( 'app_route_network' ) ,
            'control' : root + url_for( 'app_route_control' ) ,
        } ,