コード例 #1
0
        title = request.form.get("title", "")
        details = request.form.get("details", "")
        method = request.form.get("_method", "")

        if method == "PATCH":
            process_patch_request()
        else:
            Todo.add_todo(_id=todo_id, _title=title, _details=details)
        return redirect(url_for("todos_page"))

    todos = Todo.get_all_todos()
    return render_template("index.html", todos=todos)


def process_patch_request():
    todo_id = request.form.get("todo_id_edit", "")
    title = request.form.get("todo_title_edit", "")
    details = request.form.get("todo_details_edit", "")
    Todo.update_todo(_id=todo_id, _title=title, _details=details)


@app.route("/todo/<todo_id>", methods=["DELETE"])
def todos_delete(todo_id):
    Todo.delete_todo_by_id(_id=todo_id)
    todos = Todo.get_all_todos()
    return render_template("index.html", todos=todos)


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=port)
コード例 #2
0
    data = request.form['source_code']
    code = io.StringIO(data)
    create_container(code)
    output = create_container(code)
    return output


def create_container(code):
    py_container = cli.containers.run(
        image='python:3',
        command=['python', '-c', code.getvalue()],
        volumes={os.getcwd(): {
                     'bind': '/opt',
                     'mode': 'rw',
                 }},
        name='hello_word_from_docker',
        working_dir='/opt')

    for py_container in cli.containers.list(filters={'status': 'exited'}):
        with open('/opt/py_log.txt', 'a') as f:
            f.write(str(py_container.logs()))

    output = py_container.logs()
    py_container.remove()

    return "From docker: {}".format(output.strip())


if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0')
コード例 #3
0
ファイル: index.py プロジェクト: CaptainBerg/me
            photos = [apis.Photo.create_photo_with_url(**info) for info in blob_infos]
            result["status"] = "ok"
            result["photos"] = photos
        except Exception, e:
            from settings import logging
            logging.exception("error in upload_handler:")
            result["error"] = unicode(e)
            result["status"] = "error"

        return jsonify(result)


########################################
## Start Application
########################################
if RUNTIME_ENV == "bae":
    from bae.core.wsgi import WSGIApplication
    application = WSGIApplication(app)

elif RUNTIME_ENV == "sae":
    import sae
    application = sae.create_wsgi_app(app)

elif RUNTIME_ENV == "local":
    application = app
    if __name__ == "__main__":
        app.run(debug=True)

elif RUNTIME_ENV in ("gae", "gae_dev"):
    application = app
コード例 #4
0
		url=request.url_root)
	articles = db_session.query(Post).order_by(Post.creation.desc())\
	.limit(5).all()
	for article in articles:
		feed.add(article.title,
			article.content.decode('utf-8'),
			content_type='html',
			author=article.author,
			url=make_external(article.title),
			updated=article.creation,
			published=article.creation)
	return feed.get_response()

@login_required
@app.route('/logout/')
def logout():
	user_session['username'] = ''
	return redirect(url_for('index'))
	
@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html')

@app.route('/error/')
def error_page():
	return render_template('error.html')

if __name__ == '__main__':
	port = int(os.environ.get('PORT', 5000))
	app.run(host='0.0.0.0', port=port, debug=True)
コード例 #5
0
ファイル: main.py プロジェクト: xuongtrantrieu/backend_mongo
from settings import (
    app,
    load,
    DEV_ENVIRONMENT,
    PRD_ENVIRONMENT,
    CURRENT_ENVIRONMENT,
    CERT_FILE_PATH,
    KEY_FILE_PATH,
)

if __name__ == '__main__':
    load()

    if CURRENT_ENVIRONMENT == DEV_ENVIRONMENT:
        app.run(host='0.0.0.0',
                port='5000',
                ssl_context=(CERT_FILE_PATH, KEY_FILE_PATH))
    elif CURRENT_ENVIRONMENT == PRD_ENVIRONMENT:
        app.run()
    else:
        pass
コード例 #6
0
class Ejercicio2Resource(Resource):
    def get(self):
        from icmplib import ping
        if ping(os.environ.get('VYOS_IP'), count=1).is_alive:
            return {'ejercicio2': 'OK'}
        else:
            return {'ejercicio2': 'Error'}, 400


class Ejercicio3Resource(Resource):
    def get(self):
        import requests
        try:
            result = requests.get('http://172.20.0.3')
            if result.status_code == 200:
                return {'ejercicio3': 'OK'}
            else:
                return {'ejercicio3': 'Error'}, 400
        except:
            return {'ejercicio3': 'Error'}, 400


api.add_resource(Ejercicio1Resource, os.environ['EJERCICIO_1'])
api.add_resource(Ejercicio2Resource, os.environ['EJERCICIO_2'])
api.add_resource(Ejercicio3Resource, os.environ['EJERCICIO_3'])

if __name__ == "__main__":
    # As the app is running inside a container I need to publish using container IP address
    host_ip_address = socket.gethostbyname(socket.gethostname())
    app.run(host=host_ip_address, port=5000, debug=True)
コード例 #7
0
ファイル: run.py プロジェクト: huangpd/flask_demo
            {
                'name': u'订单列表',
                'url': url_for('order.order_list_view'),
                'is_show': is_show('user')
            },
        ]
    }]
    return {'menu_list': menu_list, 'user': g.user}


if __name__ == '__main__':

    @app.route('/static/upload/<path:filename>')
    def show_img_file(filename):
        return send_from_directory(os.path.join(static_dir, 'upload'),
                                   filename)

    @app.route('/static/<filename>')
    def show_favicon_file(filename):
        return send_from_directory(static_dir, filename)

    @app.route('/static/js/<path:filename>')
    def show_js_file(filename):
        return send_from_directory(os.path.join(static_dir, 'js'), filename)

    @app.route('/static/css/<path:filename>')
    def show_css_file(filename):
        return send_from_directory(os.path.join(static_dir, 'css'), filename)

    app.run(host='0.0.0.0', port=5000, debug=app.debug)
コード例 #8
0
ファイル: main.py プロジェクト: beudbeud/bookstore
    flask_login.login_user(registered_user, remember=remember_me)
    flash('Welcome to Bookstore')
    return redirect(request.args.get('next') or '/')


@app.route('/logout')
def logout():
    flask_login.logout_user()
    return redirect('/')


@app.route('/settings')
@flask_login.login_required
def settings():
    return 'Settings'


@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id))


@app.before_request
def before_request():
    g.user = flask_login.current_user


if __name__ == "__main__":
    # Only for debugging while developing
    app.run(host='0.0.0.0', debug=True, port=80)
コード例 #9
0
    user.clear_auth_token()
    return jsonify({"message": "Logged out"})


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


@app.route("/update/", methods=["POST"])
@login_required
def update():
    return jsonify({"message": "update"})


@app.route("/api/", methods=["GET"])
@token_required
def api_index():
    return jsonify({"message": "api view"})


@app.route("/api/update/", methods=["POST"])
@token_required
def api_update():
    return jsonify({"message": "api update"})


if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=5000)
コード例 #10
0
ファイル: app.py プロジェクト: huyxdong/flaskAPI
# Update a person in a list of residential
@app.route('/residential/<int:passport>', methods=['PATCH'])
@token_required
def update_person(passport):
    request_data = request.get_json()
    if 'name' in request_data:
        Person.update_person_name(passport, request_data['name'])
    if 'age' in request_data:
        Person.update_person_age(passport, request_data['age'])
    response = Response('', status=204)
    response.headers['Location'] = '/residential/' + str(passport)
    return response


# Delete a person in a list of residential
@app.route('/residential/<int:passport>', methods=['DELETE'])
@token_required
def delete_person(passport):
    if Person.delete_person(passport):
        response = Response('', 204)
        return response
    errorMsg = {"error": "This person doesn't exist!"}
    response = Response(json.dumps(errorMsg),
                        status=400,
                        mimetype='application/json')
    return response


if __name__ == '__main__':
    app.run(debug=True, port=5005)
コード例 #11
0
ファイル: app.py プロジェクト: Gott50/mailserver
        if mail_once:
            if username in all_mails:
                if data in all_mails[username]:
                    result = "already send Mail to %s" % username
                    app.logger.warning(result)
                    return result
                all_mails[username] += [data]
            else:
                all_mails[username] = [data]
            app.logger.warning("all_mails: %s" % all_mails)

        email = str(data["email"]).replace('\n', ' ')
        subject = str(data["subject"]).replace('\n', ' ')
        body = data["body"]
        msg = Message(body=body, recipients=[email], subject=subject)
        mail.send(msg)

        result = "send Mail to: %s; with subject: %s; with body: %s" % (
            email, subject, body)
        app.logger.warning(result)
        return result

    except KeyError as e:
        app.logger.error("KeyError: %s" % e)
        return "KeyError", 501  # Not Implemented


if __name__ == '__main__':
    app.run(port=7070)
コード例 #12
0
from settings import app,api
from resources import *

#Comments Urls

api.add_resource(New_Movie_Review, '/review/new/<movie_id>')
api.add_resource(Edit_Review, '/review/edit/<review_id>')
api.add_resource(Get_Movie_Reviews, '/reviews/get/<movie_id>')
api.add_resource(New_Movie, '/movie/new')
api.add_resource(Edit_Movie, '/movie/edit/<movie_id>')
api.add_resource(Get_Movie_Details, '/movie/get/<movie_id>')
api.add_resource(Get_Movies, '/movies/get')
api.add_resource(Get_Recommendation, '/movies/recommendations/<user_id>')
api.add_resource(Review_Summarization, '/reviews/summarization/<movie_id>')
api.add_resource(New_User, '/new/user')


if __name__ == '__main__':
    app.run('127.0.0.1', 8000)
コード例 #13
0
# ------------------------------------------------------------------------------------------------- #


@app.route('/about')
def about():
    return render_this_page('about.html', 'about us')


@app.errorhandler(404)
def error_404(e):
    return render_this_page('404.html', '404'), 404


@app.route('/message')
def error_page(title, img):
    return render_this_page('error.html', title, img)


@app.route('/test')
def test():
    # return render_template('home.html')
    return render_this_page('404.html', '404')


# ------------------------------------------------------------------------------------------------- #

if __name__ == '__main__':
    db.create_all()
    app.run(threaded=True, port=5000, debug=True)
    # db.close()
コード例 #14
0
        user = AuthToken.get(AuthToken.token == token).user
        auth_user(request, user)
    except (AttributeError, ValueError, AuthToken.DoesNotExist):
        pass


# @app.middleware('request')
# async def authenticate_middleware(request):
#     session_user = request['session'].get('user')
#     if session_user:
#         try:
#             user = User.get(User.username == session_user['username'])
#         except User.DoesNotExist:
#             pass
#         else:
#             request['user'] = user
#     # return request


@app.route("/")
async def root(request):
    return json({"hello": "world"})


# create_tables()

if __name__ == "__main__":
    WORKERS = int(os.environ.get('WORKERS', 1))
    # app.run(host="0.0.0.0", port=8000, debug=False)
    app.run(host="0.0.0.0", port=8000, debug=DEBUG, workers=WORKERS)
コード例 #15
0

@app.route('/speakers')
@auth.login_required
def speakers():
    from collections import defaultdict
    names = data_s.iloc[:, 0].values.tolist()
    name_dict = defaultdict(list)
    for n in names:
        name_dict[n[0].upper()].append(n)
    sorted_names = sorted(name_dict.items(), key=lambda x: x[0])
    return jsonify(sorted_names)


@app.route('/party')
@auth.login_required
def party():
    from collections import defaultdict
    parties = data_s.iloc[:, 1].values.tolist()
    parties = list(set(parties))
    party_dict = defaultdict(list)
    for p in parties:
        party_dict[p[0].upper()].append(p)
    sorted_party = sorted(party_dict.items(), key=lambda x: x[0])
    return jsonify(sorted_party)


if __name__ == '__main__':
    # 以后启动在 terminal里 python app.py
    app.run(host='0.0.0.0', port=5000, debug=True)
コード例 #16
0
                            request_data["longitude"],
                            request_data["latitude"],
                            request_data["elevation"])
            response = Response("", 201, mimetype="application/json")
            response.headers["Location"] = "/planes/" + str(unique_id)
            return response
    else:
        invalidPlaneObjectErrorMessage = {
            "error": "Invalid plane object passed in request"
        }
        response = Response(json.dumps(invalidPlaneObjectErrorMessage),
                            400,
                            mimetype="application/json")
        return response


@app.route("/planes/<string:unique_id>", methods=["DELETE"])
def delete_plane(unique_id):
    is_successful = Plane.delete_plane(unique_id)
    if (is_successful):
        response = Response("", status=204)
    else:
        errorMsg = {"error": "Plane does not exist for date/time"}
        response = Response(json.dumps(errorMsg),
                            status=404,
                            mimetype="application/json")
    return response


app.run(port=5000)
コード例 #17
0
"""
Само веб приложение.

"""
from flask import request

from views import *
from settings import app

if __name__ == '__main__':
    app.run(host=app.config['HOST'],
            port=app.config['PORT'],
            debug=app.config['FLASK_DEBUG'])
コード例 #18
0
from settings import app
from views import index, add_query, skip

# set urls
app.add_url_rule('/', 'index', index, methods=["GET"])
app.add_url_rule('/add_query', 'add_query', add_query, methods=["POST"])
app.add_url_rule('/skip', 'skip', skip, methods=["GET"])


# run app
if __name__ == '__main__':
    # db.create_all()                              # create a new database at launch
    app.run(host='0.0.0.0', port=8080, debug=False)
コード例 #19
0
ファイル: index.py プロジェクト: yangjiandong/me
    from settings import BLOB_SERVING_URL

    @app.route("%s/<blob_key>" % BLOB_SERVING_URL, methods=['GET'])
    def send_blob(blob_key):
        from flask import make_response
        from tools import make_blob_file_header

        headers = make_blob_file_header(blob_key)
        headers["Content-Type"] = "image/jpeg"
        headers["Cache-Control"] = "max-age=29030400, public"
        response = make_response()
        response.headers.extend(headers)
        return response


########################################
## Start Application
########################################
if RUNTIME_ENV in ("bae",):
    from bae.middleware.profiler import ProfilingMiddleware
    application = ProfilingMiddleware(app)

    from bae.core.wsgi import WSGIApplication
    application = WSGIApplication(application)

elif RUNTIME_ENV in ("local",):    
    app.run(host='0.0.0.0',debug=True)

elif RUNTIME_ENV in ("gae", "gae_dev"):
    application = app
コード例 #20
0
@app.route('/newAdmin')
def admin():
    return '<h1>This page will allow registeration of new admin</h1>'

@app.route('/blog/<blogType>')
def blog(blogType):
    posts = models.BlogObject.query.all()
    return render_template('blogDisplay.html', blogType=blogType, posts=posts)

@app.route('/blogform', methods=['GET', 'POST'])
def blogform():
    
    form = RegisterForm()

    if form.validate_on_submit():
        print(""+form.blogType.data+" "+form.title.data+" "+form.description.data+" "+form.user.data+" "+form.image.data.filename)
        file = form.image.data
        filename = secure_filename(file.filename)
        file.save(os.path.join(r'C:\Users\Alexander Parris\Desktop\Projects\Websites\ABPdotCOM\ABPdotCOM\static\images', filename))
        user = models.User.query.get(1)
        addPost(form.blogType.data, form.title.data, url_for('static', filename='images/'+filename), form.description.data, user)
        posts = models.BlogObject.query.all()
        return render_template('blogDisplay.html', blogType="whatever", posts=posts)
        return '<h1>{}</h1>'.format(filename)

    return render_template('form.html', form=form)


if __name__=='__main__':
    app.run(debug=True, port=8080)
コード例 #21
0
ファイル: app.py プロジェクト: maheshsovani/python-server
        Book.update_book_name(isbn, request_data['name'])

    if "price" in request_data:
        Book.update_book_price(isbn, request_data['price'])

    response = Response("", status=204)
    response.headers['Location'] = f'{isbn}'
    return response


@app.route('/books/<int:isbn>', methods=['DELETE'])
@token_required
def delete_book_in_store(isbn):
    is_successful = Book.delete_book(isbn)

    if is_successful:
        response = Response("", status=204)
        return response

    book_not_found_error = {
        error: "Requested book for delete not found in collection"
    }
    response = Response(json.dumps(book_not_found_error),
                        status=404,
                        mimetype='application/json')

    return response


app.run(port=8080)
コード例 #22
0
@app.route('/animals/<int:animal_id>', methods=['DELETE'])
def delete_animal(animal_id):
    """Delete animal by id

    :param animal_id: id of deleting animal
    :return: response
    """
    token = request.args.get('token')
    if valid_token(token, app.config['SECRET_KEY']):
        return Response(invalid_token_error_msg,
                        status=401,
                        mimetype='application/json')

    if Animal.check_animal_before_delete(animal_id):
        return Response(dumps(invalid_id_error_msg),
                        status=401,
                        mimetype='application/json')
    else:
        if check_center_before_delete(get_access().center_id, animal_id):
            Animal.delete_animal(request, animal_id)
            return Response('', status=200, mimetype='application/json')
        else:
            return Response(exists_animal_in_center_error_msg,
                            status=200,
                            mimetype='application/json')


if __name__ == '__main__':
    app.static_folder = 'static'
    app.run(port=5001)
コード例 #23
0
ファイル: main.py プロジェクト: Igor1py/social-network
from settings import app, DEBUG, LOGGING_CONFIG
from flask import jsonify
from flask_cors import CORS
from exceptions import AppException
from routes import *

CORS(app)


@app.after_request
def after_request(response):
    response.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000'
    response.headers[
        'Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
    response.headers[
        'Access-Control-Allow-Methods'] = 'GET,PUT,POST,DELETE,OPTIONS'
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    return response


@app.errorhandler(AppException)
def handle_error(error):
    app.logger.error(error.message)
    return jsonify(error.to_dict()), error.status_code


if __name__ == '__main__':
    if not DEBUG:
        dictConfig(LOGGING_CONFIG)
    app.run(debug=DEBUG)
コード例 #24
0
    "Logout",
    "PartnerBrandManager",
    "PartnerOrderManager",
    "OrderManager",
    "GetStaticAddress",
    "UserManagement",
]


@app.before_request
def process():
    path = request.endpoint
    if path in verify_paths:
        token = request.args.get("token", None)
        if token is None:
            return jsonify({
                "error_id": AuthError.code,
                "error_msg": AuthError.__name__,
            })
        else:
            verify_res = verify_token(token)
            if not verify_res:
                return jsonify({
                    "error_id": AuthError.code,
                    "error_msg": AuthError.__name__,
                })


if __name__ == '__main__':
    app.run(port=8090)
コード例 #25
0
ファイル: app.py プロジェクト: prkstaff/k8s-provision
                        int(request.args.get("to")))
                    post_date = post_value['date'].split(" GMT")[0]
                    post_date = datetime.strptime(post_date,
                                                  "%a %b %d %Y %H:%M:%S")

                    if not from_time < post_date < to_time:
                        del data_copy['users'][user_index]['posts'][post_index]
                        if len(data_copy['users'][user_index]['posts']) == 0:
                            del data_copy['users'][user_index]
                if "tag" in request.args:
                    tag = request.args.get("tag")
                    if tag not in post_value['tags']:
                        del data_copy['users'][user_index]['posts'][post_index]
                        if len(data_copy['users'][user_index]['posts']) == 0:
                            del data_copy['users'][user_index]
        if "lang" in request.args:
            for user_index, user_value in reversed(
                    list(enumerate(data_copy['users']))):
                if user_value['language'] != request.args.get('lang'):
                    del data_copy['users'][user_index]
        return Response(json.dumps(data_copy),
                        status=200,
                        mimetype="application/json")
    if len(request.args) > 0:
        return Response("", status=501, mimetype='application/json')
    return Response("", status=422, mimetype='application/json')


if __name__ == "__main__":
    app.run(host='127.0.0.1', port=8080)
コード例 #26
0
    except Exception as exc:
        app.logger.error("GET /bot/stop/%s Exception: %s" % (account, exc))
        return str(exc), 500


@app.route('/api/bot/start/<account>', methods=['GET'])
def start(account):
    app.logger.warning("GET /bot/start/%s" % account)
    try:
        return requests.get('%s/bot/start/%s' %
                            (os.environ['APP_BOT_GATEWAY'], account))
    except Exception as exc:
        app.logger.error("GET /bot/start/%s Exception: %s" % (account, exc))
        return str(exc), 500


@app.route('/api/mail/', methods=['POST'])
def mail():
    data = json.loads(request.data)
    app.logger.warning("POST /mail: %s" % data)
    try:
        return requests.post('%s/mail/' % os.environ['APP_MAIL_GATEWAY'],
                             request.data)
    except Exception as exc:
        app.logger.error("POST /bot/login Exception: %s" % (exc))
        return str(exc), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)
コード例 #27
0
from flask import render_template
from settings import app
import sqlite3


@app.route('/')
def index():
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    cursor.execute('SELECT * from palestrantes')
    palestrantes = cursor.fetchall()
    return render_template('index.html', palestrantes=palestrantes)


if __name__ == '__main__':
    app.run(port=8001)
コード例 #28
0
ファイル: app.py プロジェクト: kirillsCode/PyRestApi
# { 'name': 'Harry Potter' }
@app.route('/books/<int:isbn>', methods=['PATCH'])
@token_required
def update_book(isbn):
    received = request.get_json()
    # Validate the requested data

    received['isbn'] = isbn
    if Book.edit_book(**received):
        response = Response("The book has been updated", status=201)
    else:
        response = Response("Something went wrong! Check the logs!",
                            status=400)
    return response


# DELETE
@app.route('/books/<int:isbn>', methods=['DELETE'])
@token_required
def delete_book(isbn):
    result = Book.delete_book(isbn)
    if result > 0:
        response = Response('%s books have been deleted' % result, status=201)
    else:
        response = Response("The book with such ISBN wasn't found", status=404)
    return response


if __name__ == "__main__":
    app.run()
コード例 #29
0
ファイル: vertstudios.py プロジェクト: Fusion/Vert-Flask
#####################################################################
# Routes
#####################################################################

@app.route('/')
def home():
  # Get HTML for the home page rss feed
  rssFeed = from_the_blog()
  return render_template("index.html", rssFeed=rssFeed)

@app.route('/work')
def work():
  return render_template("work.html", title="Work")

@app.route('/services')
def services():
  return render_template("services.html", title="Services")

@app.route('/about')
def about():
  return render_template("about.html", title="About")

@app.route('/sitemap/')
def sitemap():
  return render_template("sitemap.static")


if __name__ == "__main__":
	app.run()
コード例 #30
0
ファイル: main.py プロジェクト: liuwq168/nlp-project1
def fetch_news():
    news = random_choose(100)
    return render_template('main.html', n=news)


@app.route('/p')
def p():
    news_id = request.args.get('id')
    news = W.query.get(news_id)
    p = fetch(news.content)
    return render_template('p.html',
                           t=news.title,
                           c=news.content,
                           p=p[0],
                           cp=p[1])


@app.route('/')
def page():
    return render_template('main.html')


@app.route('/s')
def s():
    from model import say_represents
    return render_template('s.html', s=say_represents)


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=11001)
コード例 #31
0
ファイル: server.py プロジェクト: Instagram-Tools/manager
        return str(exc), 500


@app.route('/bot/start/<account>', methods=['GET'])
def start(account):
    app.logger.warning("GET /bot/start/%s" % account)
    try:
        return activity.start(account)
    except Exception as exc:
        app.logger.error("GET /bot/start/%s Exception: %s" % (account, exc))
        return str(exc), 500


@app.route('/bot/login/', methods=['POST'])
def try_login():
    data = json.loads(request.data)
    app.logger.warning("POST /bot/login: %s" % data)
    try:
        return activity.start_try_login(username=data.get("username",
                                                          "").lower(),
                                        password=data.get('password'),
                                        email=data.get('email'),
                                        sec_code=data.get('sec_code'))
    except Exception as exc:
        app.logger.error("POST /bot/login Exception: %s" % (exc))
        return str(exc), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8765)
コード例 #32
0
ファイル: main.py プロジェクト: alp78/Google-Cloud-Platform
@app.route('/delete/<isbn>')
def delete_book(isbn):
    if (Book.delete_book(isbn)):
        deletionCompletedMsg = {
            'success':
            'Book with ISBN {0} was deleted from collection.'.format(isbn)
        }
        response = Response(json.dumps(deletionCompletedMsg),
                            status=200,
                            mimetype='application/json')
        return response
    invalidBookObjectErrorMsg = {'error': 'Book with this ISBN was not found.'}
    response = Response(json.dumps(invalidBookObjectErrorMsg),
                        status=404,
                        mimetype='application/json')
    return response


@app.errorhandler(500)
def server_error(e):
    # Log the error and stacktrace.
    logging.exception('An error occurred during a request.')
    return 'An internal error occurred.', 500


# for testing the app in localhost
if __name__ == '__main__':
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine. See entrypoint in app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)
コード例 #33
0
from flask_restful import Api

app.url_map.strict_slashes = False

# Swagger configuration
SWAGGER_CONFIG = config.get('SWAGGER_CONFIG')

api = Api(app, )

cel.autodiscover_tasks(["services.background.jobs"])

# CORS whitelisting.
CORS(app, origins=config['CORS_ORIGIN_REGEX_WHITELIST'])

# Registering routes.
register_urls(api)


@app.route("/")
@app.route("/api")
def index():
    return json.dumps({
        "message":
        "Welcome to twitter sentimental analysis backend service!! TEST-API"
    })


if __name__ == '__main__':
    os.environ['APP_CONFIG'] = 'config.LocalConfig'
    app.run(debug=True, host='0.0.0.0', port=8000, threaded=True)
コード例 #34
0
@app.route('/export', methods=['POST'])
@toker_required
def export_csv(current_user):
    '''
        Exporta um file CSV com informacoes dos medicamentos mais vendidos em um periodo de 
        tempo fornecido pelo usuario 

        :type current_user: string
        :param current_user: Usuario logado no sistema

    '''
    check_access(current_user)

    data = request.get_json()
    list_medicamentos = get_lista_medicamentos(data)

    df = pd.DataFrame(list_medicamentos)
    df.to_csv("TOPMedicamentos_{}_{}.csv".format(data['start'], data['end']))

    return jsonify({
        'message': 'Download CSV completado',
        'data': list_medicamentos
    })


# Inicia o sistema
# ===================================================================================
if __name__ == '__main__':
    app.run(debug=True)
コード例 #35
0
ファイル: app.py プロジェクト: drachpy/flask-rest
from settings import app, api
from util.Logger import InfoLogger
import resources.routes


# entry point
if __name__ == '__main__':
    info = InfoLogger(__name__)
    info.log("Started...")
    app.run(debug=False, host='0.0.0.0', port=8081)