コード例 #1
0
ファイル: main.py プロジェクト: vasukushwah/flask-vue-term
from gevent import monkey
monkey.patch_all()
import json
from flask import Flask, render_template
from flask_sockets import Sockets
import json
from terminal import Terminal,TerminalManager
import logging 
from gevent import pywsgi
import argparse
from geventwebsocket.handler import WebSocketHandler

flask_app = Flask(__name__,static_folder = "./dist/static", template_folder = "./dist")
sockets = Sockets(flask_app)

logging.basicConfig(level=logging.INFO,format='[%(asctime)s] - %(levelname)s - %(message)s')



@sockets.route('/term')
def echo_socket(ws):

    term = TerminalManager(ws)
    id = term.create(autoclose=True,log=logging)
    obj = term.terminals[id]
    while not ws.closed:
        message = ws.receive()
        if message is None:
            term.kill(id)
        else:
            data = json.loads(message)
コード例 #2
0
ファイル: unity.py プロジェクト: alsu0088/TonsleyLEDManager
    def __init__(self, dims):
        self.dims = dims
        import numpy as np
        self.np = np

        from flask import Flask, render_template, request
        from flask_sockets import Sockets
        import json
        from random import randint
        from itertools import cycle
        from matplotlib import cm
        num_cols = 512
        # Pick a colour map from here: https://matplotlib.org/users/colormaps.html
        rainbow = cm.get_cmap('PuBu', num_cols)
        self.sky_colours = [[int(c * 256) for c in rainbow(i)[:-1]]
                            for i in range(num_cols)]
        self.sky_colours = cycle(self.sky_colours + self.sky_colours[::-1])
        app = Flask('UnityGame')
        sockets = Sockets(app)
        self.things = [{
            'type': 'cloud',
            'xpos': 90,
            'ypos': 1,
            'frame': 0,
            'frame_rate': 0,
            'velocity': 0.2,
        }, {
            'type': 'gull',
            'xpos': 90,
            'ypos': 1,
            'frame': 0,
            'frame_rate': 0.2,
            'velocity': 1,
        }]
        self.things_templates = {
            'cloud': {
                'colours': [[0xd8, 0xad, 0xde], [253, 245, 251]],
                'template':
                np.array([[
                    # gratuitously stolen from: https://cdn.dribbble.com/users/1113/screenshots/150244/pixelcloud-dribbble.png
                    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 1, 1, 0, 0, 0, 0],
                    [0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 0, 0, 0],
                    [0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 1, 0, 0, 0],
                    [0, 1, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 1, 0, 0],
                    [0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 0],
                    [1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                    [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                    [1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1],
                    [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
                ]])
            },
            'gull': {
                'colours': [[77, 77, 77], [253, 245, 251]],
                'template':
                np.array([[
                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0],
                    [0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0],
                    [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0],
                ],
                          [
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0],
                              [1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0],
                              [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
                          ]])
            },
            'boat': {
                'template': [
                    # [0,0, 0, 1, 0, 0,0],
                    # [0,0, 1, 1, 1, 0,0],
                    # [0,1, 1, 1, 1, 1,0],
                    # [0,0, 0, 1, 0, 0,0],
                    # [1,1, 0, 1, 0, 1,1],
                    # [0,1, 1, 1, 1, 1,0],
                    # [0,0, 1, 1, 1, 0,0]
                    [0, 0, 0, 0, 0, 0, 0, 2],
                    [0, 0, 0, 0, 0, 0, 2, 3],
                    [0, 1, 1, 1, 0, 2, 0, 3],
                    [1, 1, 1, 1, 1, 1, 0, 3],
                    [0, 1, 1, 1, 1, 0, 0, 3]
                ]
            }
        }
        self.current_players = {}
        game_x_min = 0
        game_x_max = 100
        self.game_y_max = 20
        boat_velocity = 0.5
        initial_hook_velocity = .1
        app_port = 5000

        ug_socket = {'ws': None}

        def make_player(ws):
            player = {
                'type':
                'boat',
                'colour': [[randint(0, 255) for _ in range(3)], [90, 60, 20],
                           [255, 255, 255]],
                'hook_position':
                0,
                'hook_velocity':
                0,
                'xpos':
                randint(game_x_min, game_x_max),
                'ypos':
                8,
                'velocity':
                0,
                'score':
                0,
                'id':
                ws.handler.client_address
            }
            self.current_players[ws] = player
            # inform the unity game about this?

        @sockets.route('/unity')
        def unity_client_socket(ws):
            # should check that unity is running locally only
            if ug_socket['ws'] is not None or ws.handler.client_address[
                    0] != '127.0.0.1':
                return
            ug_socket['ws'] = ws

            while not ws.closed:
                # do stuff here i guess...
                message = ws.receive().lower()
                if message == 'player_state':
                    ws.send(json.dumps(self.current_players.items()))
            ug_socket['ws'] = None

        @sockets.route('/client')
        def device_client_socket(ws):
            make_player(ws)
            ws.send(json.dumps(self.current_players[ws]))
            while not ws.closed:
                message = ws.receive()
                if message is None:
                    break
                message = message.lower()
                player_state = self.current_players[ws]
                print("{}: {}".format(player_state['id'][0], message))
                event_handlers = {'left': None}
                if message == 'left':
                    if player_state['hook_velocity'] == 0:
                        player_state['velocity'] = -boat_velocity
                elif message == 'right':
                    if player_state['hook_velocity'] == 0:
                        player_state['velocity'] = boat_velocity
                elif message == 'stop':
                    player_state['velocity'] = 0
                elif message == 'hook':
                    # handle hook drop gameplay
                    # player_state['score'] += 1
                    if player_state['hook_velocity'] == 0:
                        player_state['velocity'] = 0
                        player_state['hook_velocity'] = initial_hook_velocity
                        # ug_socket['ws'].send('hook dropped')
                self.send_client_state(ws)
            del self.current_players[ws]

        import uuid
        qr_codes = set([uuid.uuid4().hex])

        @app.route('/')
        def home():
            # check they sent a a valid qr code
            # artworkpc.isd.ad.flinders.edu.au:5000/?qr=a6rt5grtg566bt
            qr = request.args.get('qr')
            # if qr not in qr_codes:
            #     return "YOU CANT PLAY WITHOUT A QR CODE"
            with open('fishgame.html') as f:
                fish_html = f.read()
            return fish_html

        def flaskThread():
            from gevent import pywsgi
            from geventwebsocket.handler import WebSocketHandler
            import socket
            host = socket.gethostbyname(socket.gethostname())
            server = pywsgi.WSGIServer((host, app_port),
                                       app,
                                       handler_class=WebSocketHandler)
            print("Starting server on: http://{}:{}".format(*server.address))
            server.serve_forever()

        import thread
        thread.start_new_thread(flaskThread, ())
コード例 #3
0
ファイル: __init__.py プロジェクト: zhaoshiling1017/w5
# encoding:utf-8
import os
import configparser
# from loguru import logger
from flask_cors import CORS
from flask_orator import Orator
from flask_redis import FlaskRedis
from flask_sockets import Sockets
from core.view import Decorator
from flask import (Flask, send_from_directory)

version = "0.1"

db = Orator()
redis = FlaskRedis()
sockets = Sockets()


# def init_log():
#     base = "/Users/sanjin/work/w5/x_w5/logs"
#
#     info_path = os.path.join(base, 'info.{time:YYYY-MM-DD}.log')
#     error_path = os.path.join(base, 'error.{time:YYYY-MM-DD}.log')
#
#     logger.remove()
#
#     logger_format = "{time:YYYY-MM-DD HH:mm:ss,SSS} [{thread}] {level} {file} {line} - {message}"
#
#     logger.add(info_path, format=logger_format, enqueue=True, rotation="00:00", retention='10 days',
#                encoding='utf-8', level='INFO')
#
コード例 #4
0
import os

from celery import Celery
from flask import Flask
from flask_alembic import Alembic
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_sockets import Sockets

from server.tools import data_generator

alembic = Alembic()
db = SQLAlchemy()
ma = Marshmallow()
ws = Sockets()


def create_app(config=None):
    config = config or os.environ['CONFIG']
    app = Flask(__name__)

    app.config.from_object(config)
    alembic.init_app(app)
    db.init_app(app)
    ma.init_app(app)
    ws.init_app(app)

    from server import views
    from server import models

    app.register_blueprint(views.api.blueprint)
コード例 #5
0
def instantiate_app_with_views(context, schema, app_path_prefix):
    app = Flask(
        "dagster-ui",
        static_url_path=app_path_prefix,
        static_folder=os.path.join(os.path.dirname(__file__), "./webapp/build"),
    )
    subscription_server = DagsterSubscriptionServer(schema=schema)

    # Websocket routes
    sockets = Sockets(app)
    sockets.add_url_rule(
        "{}/graphql".format(app_path_prefix),
        "graphql",
        dagster_graphql_subscription_view(subscription_server, context),
    )

    # HTTP routes
    bp = Blueprint("routes", __name__, url_prefix=app_path_prefix)
    bp.add_url_rule(
        "/graphiql", "graphiql", lambda: redirect("{}/graphql".format(app_path_prefix), 301)
    )
    bp.add_url_rule(
        "/graphql",
        "graphql",
        DagsterGraphQLView.as_view(
            "graphql",
            schema=schema,
            graphiql=True,
            graphiql_template=PLAYGROUND_TEMPLATE.replace("APP_PATH_PREFIX", app_path_prefix),
            executor=Executor(),
            context=context,
        ),
    )

    bp.add_url_rule(
        # should match the `build_local_download_url`
        "/download/<string:run_id>/<string:step_key>/<string:file_type>",
        "download_view",
        download_log_view(context),
    )

    bp.add_url_rule(
        "/download_debug/<string:run_id>",
        "download_dump_view",
        download_dump_view(context),
    )

    # these routes are specifically for the Dagit UI and are not part of the graphql
    # API that we want other people to consume, so they're separate for now.
    # Also grabbing the magic global request args dict so that notebook_view is testable
    bp.add_url_rule("/dagit/notebook", "notebook", lambda: notebook_view(request.args))
    bp.add_url_rule("/dagit_info", "sanity_view", info_view)

    index_path = os.path.join(os.path.dirname(__file__), "./webapp/build/index.html")

    def index_view(_path):
        try:
            with open(index_path) as f:
                return (
                    f.read()
                    .replace('href="/', 'href="{}/'.format(app_path_prefix))
                    .replace('src="/', 'src="{}/'.format(app_path_prefix))
                    .replace(
                        '<meta name="dagit-path-prefix"',
                        '<meta name="dagit-path-prefix" content="{}"'.format(app_path_prefix),
                    )
                )
        except FileNotFoundError:
            raise Exception(
                """Can't find webapp files. Probably webapp isn't built. If you are using
                dagit, then probably it's a corrupted installation or a bug. However, if you are
                developing dagit locally, your problem can be fixed as follows:

                cd ./python_modules/
                make rebuild_dagit"""
            )

    app.app_protocol = lambda environ_path_info: "graphql-ws"
    app.register_blueprint(bp)
    app.register_error_handler(404, index_view)

    # if the user asked for a path prefix, handle the naked domain just in case they are not
    # filtering inbound traffic elsewhere and redirect to the path prefix.
    if app_path_prefix:
        app.add_url_rule("/", "force-path-prefix", lambda: redirect(app_path_prefix, 301))

    CORS(app)
    return app
コード例 #6
0
from os.path import join as pjoin
import subprocess
import json

import flask
from flask import Flask, request, Response
from flask_sockets import Sockets

import logging
logging.basicConfig(level=logging.DEBUG)

db_dir = "./db"

application = Flask(__name__, static_folder="static", static_url_path='')
sockets = Sockets(application)

socket = None


@application.route("/modelxml", methods=['GET'])
def get_model_mesh_xml():
    return flask.send_from_directory('db', 'complex.xml')


@application.route("/model/sofa_seat.000.mesh.xml", methods=['GET'])
def get_model_sofa_mesh_xml():
    return flask.send_from_directory('db', 'sofa_seat.000.mesh.xml')


@application.route("/model/sofa_seat.000.mesh.mesh", methods=['GET'])
def get_model_sofa_mesh_mesh():
コード例 #7
0
def create_socket():
    socket = Sockets()
    chess_init_socket(socket)

    return socket
コード例 #8
0
ファイル: app.py プロジェクト: Kazuya95/dagster
def create_app(handle,
               pipeline_run_storage,
               scheduler=None,
               use_synchronous_execution_manager=False):
    check.inst_param(handle, 'handle', ExecutionTargetHandle)
    check.inst_param(pipeline_run_storage, 'pipeline_run_storage', RunStorage)
    check.opt_inst_param(scheduler, 'scheduler', Scheduler)
    check.bool_param(use_synchronous_execution_manager,
                     'use_synchronous_execution_manager')

    app = Flask('dagster-ui')
    sockets = Sockets(app)
    app.app_protocol = lambda environ_path_info: 'graphql-ws'

    schema = create_schema()
    subscription_server = DagsterSubscriptionServer(schema=schema)

    if use_synchronous_execution_manager:
        execution_manager = SynchronousExecutionManager()
    else:
        execution_manager = MultiprocessingExecutionManager()

    print('Loading repository...')

    if Features.SCHEDULER.is_enabled:
        context = DagsterGraphQLContext(
            handle=handle,
            execution_manager=execution_manager,
            pipeline_runs=pipeline_run_storage,
            scheduler=scheduler,  # Add schedule argument
            version=__version__,
        )
    else:
        context = DagsterGraphQLContext(
            handle=handle,
            execution_manager=execution_manager,
            pipeline_runs=pipeline_run_storage,
            version=__version__,
        )

    app.add_url_rule(
        '/graphql',
        'graphql',
        DagsterGraphQLView.as_view(
            'graphql',
            schema=schema,
            graphiql=True,
            # XXX(freiksenet): Pass proper ws url
            graphiql_template=PLAYGROUND_TEMPLATE,
            executor=Executor(),
            context=context,
        ),
    )
    sockets.add_url_rule(
        '/graphql', 'graphql',
        dagster_graphql_subscription_view(subscription_server, context))

    # these routes are specifically for the Dagit UI and are not part of the graphql
    # API that we want other people to consume, so they're separate for now.
    # Also grabbing the magic global request args dict so that notebook_view is testable
    app.add_url_rule('/dagit/notebook', 'notebook',
                     lambda: notebook_view(request.args))

    app.add_url_rule('/static/<path:path>/<string:file>', 'static_view',
                     static_view)
    app.add_url_rule('/vendor/<path:path>/<string:file>', 'vendor_view',
                     vendor_view)
    app.add_url_rule('/<path:_path>', 'index_catchall', index_view)
    app.add_url_rule('/', 'index', index_view, defaults={'_path': ''})

    CORS(app)

    return app
コード例 #9
0
ファイル: __init__.py プロジェクト: luy07/moon
from flask import  Flask,url_for,render_template
from flask_sockets import Sockets
app=Flask(__name__)
socket=Sockets(app)

app.secret_key=b'\xfc\xc0\x8a0<~\x1d\x1c\x98o\xf1\x7fZQ \xd7\x0c\x9cy\x14\x14\xc2\xe4\r'


from project.views import home
from project.views import backend

app.register_blueprint(home.html)
socket.register_blueprint(home.ws)
app.register_blueprint(backend.mod)

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 400

@app.url_defaults
def add_language_code(endpoint,values):
    pass

@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
    pass
コード例 #10
0
  - IZaberFlask

- flask.Blueprint
  - IZaberFlask

base_app = IZaberFlask() - The subclassed flask.Flask

socktes = Sockets(app)
wamp = IZaberFlaskWAMP(sockets,base_app)

myapp = IZaberFlask(__name__)

"""

app = FlaskAppWrapper(izaber.flask.app)
sockets = Sockets(izaber.flask.app)
wamp = IZaberFlaskLocalWAMP(sockets, app)

izaber_flask = None


class IZaberFlask(flask.Blueprint):
    def __init__(self,
                 import_name,
                 static_folder='static',
                 static_url_path='static',
                 template_folder='templates',
                 url_prefix='',
                 subdomain=None,
                 url_defaults=None,
                 root_path=None):
コード例 #11
0
import re as rgx
import os
import eel_flask.browsers as brw
import random as rnd
import sys
import pkg_resources as pkg
import socket
import mimetypes
from flask_sockets import Sockets
from flask import abort, send_file
from flask_cors import CORS

mimetypes.add_type('application/javascript', '.js')
flask_app = Flask('eel_flask')
CORS(flask_app)
websocket = Sockets(flask_app)
_eel_js_file = pkg.resource_filename('eel_flask', 'eel_flask.js')
_eel_js = open(_eel_js_file, encoding='utf-8').read()
_websockets = []
_call_return_values = {}
_call_return_callbacks = {}
_call_number = 0
_exposed_functions = {}
_js_functions = []
_mock_queue = []
_mock_queue_done = set()

# The maximum time (in milliseconds) that Python will try to retrieve a return value for functions executing in JS
# Can be overridden through `eel_flask.init` with the kwarg `js_result_timeout` (default: 10000)
_js_result_timeout = 10000
コード例 #12
0
ファイル: api.py プロジェクト: metachris/rfid-music-player
    def create_app(self):
        """ Creates the Flask app """
        app = Flask(__name__, static_url_path='')
        app.config.update(dict(DEBUG=False))

        # Setup cors headers to allow all domains
        CORS(app)

        # Setup Flask-internal error logging
        for handler in list(logger.handlers):
            app.logger.addHandler(handler)

        # Setup error logging inside routes with automatic http responses.
        # The error will already be logged through the above added handlers,
        # so no need to log again.
        @app.errorhandler(500)
        def _internal_error(exception):
            return jsonify({
                "error": str(exception)
            }), 500

        # Setup WebSockets
        sockets = Sockets(app)

        def process_websocket_message(websocket, message):
            """ Processing of incoming websocket messages """
            logger.info("ws> %s" % message)
            websocket.send(message)  # Just echo

        @sockets.route('/ws')
        def _websocket_conn(websocket):
            self.websockets.append(websocket)
            while not websocket.closed:
                message = websocket.receive()
                if message and not websocket.closed:
                    process_websocket_message(websocket, message)
            self.websockets.remove(websocket)

        # Definition of the routes.
        @app.route("/")
        def _home():
            return send_from_directory(settings.PATH_WEB_FRONTEND, "index.html")

        @app.route('/thumbnail/<path:path>')
        def _thumbnail(path):
            logger.debug("thumbnail: %s", path)
            return send_from_directory(settings.PATH_MUSIC, path)

        @app.route('/music/<path:path>')
        def _music(path):
            logger.debug("music: %s", path)
            return send_from_directory(settings.PATH_MUSIC, path)

        @app.route('/static/<path:path>')
        def _static(path):
            logger.debug("static: %s", path)
            return send_from_directory(os.path.join(settings.PATH_WEB_FRONTEND, "static"), path)

        @app.route("/songs")
        def _api_get_songs():
            return jsonify({
                "songs": utils.get_songs()
            })

        @app.route("/tags", methods=['GET', 'POST'])
        def _api_get_tags():
            if request.method == 'POST':
                new_tag = request.json
                logger.info("new tag: %s", new_tag)
                database.add_tag(new_tag)

            return jsonify({
                "tags": database.get("tags")
            })

        @app.route("/tags/<tagId>", methods=['GET', 'POST', 'DELETE'])
        def _api_tag(tagId):
            if not database.get_tag(tagId):
                return jsonify({}), 404

            if request.method == 'DELETE':
                logger.info("API delete tag %s", tagId)
                database.delete_tag(tagId)
                return jsonify({})

            elif request.method == 'POST':
                logger.info("API update tag %s", tagId)

            return jsonify({
                "tag": database.get_tag(tagId)
            })

        @app.route("/youtube-dl/<youtubeId>")
        def _api_youtube_dl(youtubeId):
            # eg. rJWZhitXWzI
            self.youtube_download(youtubeId)
            return "download started"

        return app, sockets
コード例 #13
0
#!/usr/bin/env python

from flask import Flask, render_template, redirect, url_for, request, jsonify, make_response
from flask_sockets import Sockets
from flask_pymongo import PyMongo
import json

app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'grass'
mongo = PyMongo(app)
sock = Sockets(app)


@sock.route('/')
def echo_sock(ws):
    if True:
        roots_list = get_roots_from_db()
        ws.send(json.dumps(roots_list))

    with mongo.db.roots.watch() as watch_roots:
        for change in watch_roots:
            if change['operationType'] == 'insert' or change[
                    'operationType'] == 'delete':
                roots_list = get_roots_from_db()
                ws.send(json.dumps(roots_list))


@sock.route('/admin')
def echo_socka(wsa):
    if True:
        bids_list = get_bids_for_all()
コード例 #14
0
ファイル: Api.py プロジェクト: Wanket/RnD-py
    def init(flask: Flask) -> None:
        flask.config["SESSION_COOKIE_NAME"] = Api.__COOKIE_SESSION_NAME

        def route(path: str, **kwargs) -> Callable:
            return flask.route(f"{Api.__API_PREFIX}{path}",
                               endpoint=path,
                               **kwargs)

        @route("ping")
        @Api.__need_authorization
        @Api.__response_json
        def ping() -> Serializable:
            return Result(StatusCode.Success.name)

        @route("registration", methods=["POST"])
        @Api.__receive_or_bad_request(User)
        @Api.__response_json
        @inject.autoparams("connection")
        def registration(
                user: User,
                connection: Connection) -> Union[Response, Serializable]:
            if len(user.name) > 150:
                return Response(status=HTTPStatus.BAD_REQUEST)

            db_session = connection.serializable_session()

            if db_session.query(exists().where(
                    connection.User.user_name == user.name)).scalar():
                return Result(StatusCode.UserAlreadyExist.name)

            salt = os.urandom(32)

            db_session.add(
                DB_User(user_name=user.name,
                        password=PasswordHasher.get_hash(salt, user.password),
                        salt=salt))
            db_session.commit()

            session[Api.__COOKIE_SESSION_NAME] = UserIdPrincipal(user.name)

            return Result(StatusCode.Success.name)

        @route("authorization", methods=["POST"])
        @Api.__receive_or_bad_request(User)
        @Api.__response_json
        @inject.autoparams("connection")
        def authorization(
                user: User,
                connection: Connection) -> Union[Response, Serializable]:
            if len(user.name) > 150:
                return Response(status=HTTPStatus.BAD_REQUEST)

            db_session = connection.session()

            db_user = db_session.query(DB_User).filter(
                DB_User.user_name == user.name).first()

            if db_user is None or db_user.password != PasswordHasher.get_hash(
                    db_user.salt, user.password):
                return Result(StatusCode.InvalidUsernameOrPassword.name)

            session[Api.__COOKIE_SESSION_NAME] = UserIdPrincipal(user.name)

            return Result(StatusCode.Success.name)

        @route("send_message", methods=["POST"])
        @Api.__need_authorization
        @Api.__receive_or_bad_request(MessageToSend)
        @Api.__response_json
        @inject.autoparams("connection")
        def send_message(
                message: MessageToSend,
                connection: Connection) -> Union[Response, Serializable]:
            if len(message.text) > 280:
                return Response(status=HTTPStatus.BAD_REQUEST)

            post = Post(datetime=datetime.utcnow(),
                        author=session[Api.__COOKIE_SESSION_NAME]["name"],
                        message=message.text)

            db_session = connection.session()
            db_session.add(post)

            MessageSubscribersQueue.send_to_subscribers(
                Message(floor(post.datetime.timestamp()), post.author,
                        post.message))

            db_session.commit()

            return Result(StatusCode.Success.value)

        sockets = Sockets(flask)

        @sockets.route(f"{Api.__API_PREFIX}message_socket")
        @inject.autoparams("connection")
        def message_socket(ws: WebSocket, connection: Connection) -> None:
            if Api.__COOKIE_SESSION_NAME not in session:
                ws.close()

                return

            db_session = connection.session()

            for post in db_session.query(Post).all():
                ws.send(
                    Message(datetime=floor(post.datetime.timestamp()),
                            author=post.author,
                            text=post.message).serialize())

            with MessageSubscribersQueue.subscribe(request, ws):
                ws.receive()
コード例 #15
0
from flask_sockets import Sockets

from .controller import SocketController
from .event import EventSocketController

socket = Sockets()
コード例 #16
0
ファイル: route_manager.py プロジェクト: syntaxaire/site
    def __init__(self):

        # Set up the app and the database
        self.app = Flask(
            __name__,
            template_folder=TEMPLATES_PATH,
            static_folder=STATIC_PATH,
            static_url_path="/static",
        )
        self.sockets = Sockets(self.app)

        self.db = RethinkDB()
        self.log = logging.getLogger(__name__)
        self.app.secret_key = os.environ.get("WEBPAGE_SECRET_KEY",
                                             "super_secret")
        self.app.config["SERVER_NAME"] = os.environ.get(
            "SERVER_NAME", "pythondiscord.local:8080")
        self.app.config["PREFERRED_URL_SCHEME"] = PREFERRED_URL_SCHEME
        self.app.config[
            "WTF_CSRF_CHECK_DEFAULT"] = False  # We only want to protect specific routes

        # Trim blocks so that {% block %} statements in templates don't generate blank lines
        self.app.jinja_env.trim_blocks = True
        self.app.jinja_env.lstrip_blocks = True

        # We make the token valid for the lifetime of the session because of the wiki - you might spend some
        # time editing an article, and it seems that session lifetime is a good analogue for how long you have
        # to edit
        self.app.config["WTF_CSRF_TIME_LIMIT"] = None

        if DEBUG_MODE:
            # Migrate the database, as we would in prod
            when_ready(output_func=self.db.log.info)

        self.app.before_request(self.db.before_request)
        self.app.teardown_request(self.db.teardown_request)

        CSRF.init_app(self.app)  # Set up CSRF protection

        # Load the oauth blueprint
        self.oauth_backend = OAuthBackend(self)
        self.oauth_blueprint = make_discord_blueprint(
            DISCORD_OAUTH_ID,
            DISCORD_OAUTH_SECRET,
            DISCORD_OAUTH_SCOPE,
            login_url=DISCORD_OAUTH_REDIRECT,
            authorized_url=DISCORD_OAUTH_AUTHORIZED,
            redirect_to="main.auth.done",
            backend=self.oauth_backend)
        self.log.debug(f"Loading Blueprint: {self.oauth_blueprint.name}")
        self.app.register_blueprint(self.oauth_blueprint)
        self.log.debug("")

        # Load the main blueprint
        self.main_blueprint = Blueprint("main", __name__)
        self.log.debug(f"Loading Blueprint: {self.main_blueprint.name}")
        self.load_views(self.main_blueprint, "pysite/views/main")
        self.load_views(self.main_blueprint, "pysite/views/error_handlers")
        self.app.register_blueprint(self.main_blueprint)
        self.log.debug("")

        # Load the subdomains
        self.subdomains = ["api", "staff", "wiki"]

        for sub in self.subdomains:
            try:
                sub_blueprint = Blueprint(sub, __name__, subdomain=sub)
                self.log.debug(f"Loading Blueprint: {sub_blueprint.name}")
                self.load_views(sub_blueprint, f"pysite/views/{sub}")
                self.app.register_blueprint(sub_blueprint)
            except Exception:
                logging.getLogger(__name__).exception(
                    f"Failed to register blueprint for subdomain: {sub}")

        # Load the websockets
        self.ws_blueprint = Blueprint("ws", __name__)

        self.log.debug("Loading websocket routes...")
        self.load_views(self.ws_blueprint, "pysite/views/ws")
        self.sockets.register_blueprint(self.ws_blueprint, url_prefix="/ws")

        self.app.before_request(
            self.https_fixing_hook)  # Try to fix HTTPS issues
コード例 #17
0
ファイル: __init__.py プロジェクト: Larissa13/Mac5853
def create_app(Config):
    """
    Creates the website's pages behavior and the app's database. Returns app object and database object.
    """
    app = Flask(__name__)

    app.config.from_object(Config)
    db = SQLAlchemy()

    app.config['DEBUG'] = True

    db.app = app
    db.init_app(app)

    sockets = Sockets(app)

    @app.route('/', methods=('GET', 'POST'))
    def index():
        """
        Creates and desplays the main page (index). Returns the rendered webpage.
        """
        status_dict = {
            'done': ('success', '100'),
            'calculating': ('warning', '50'),
            'extracting words from website': ('danger', '25'),
            'formulating answer': ('info', '75'),
            'wait': ('', '0')
        }

        #TEMP VALUES
        #key = 'done'
        veredict = 'PERMITTED'
        expl_words = ['cigarro', 'tabaco', 'tragar']
        label = 'Cigarros'
        #TEMP VALUES

        url = None
        key = 'wait'
        ws_on = 'False'
        status = status_dict[key]

        if request.method == 'POST':

            if request.is_json:
                in_json = json.loads(request.get_json())
                sites = in_json['sites']
                callback = in_json['callback']
                _, _, _, key, _ = get_result(sites, True, callback=callback)

                return "calling classifier"

            else:

                url = request.form['url']
                keywords = request.form['keywords']
                force_calc = request.form.get('forcecalc') != None

                label, expl_words, veredict, key, ws_on = get_result(
                    [url], force_calc)
                status = status_dict[key]
                print("called post, websocket: " + str(ws_on))
                print(label, expl_words, veredict, key, force_calc)
        else:
            key = request.args.get('key')
            veredict = request.args.get('veredict')

            n_words = request.args.get('n_words')
            n_words = n_words if n_words is not None else 0
            expl_words = []
            for i in range(int(n_words)):
                expl_words += [request.args.get('expl_words_' + str(i))]

            label = request.args.get('label')
            url = request.args.get('url')
            status = status_dict[key] if key is not None else status_dict[
                'wait']

            if key is not None:
                req = Request(url=url, status=key)
                db.session.add(req)
                db.session.commit()
                if key == 'done':
                    update_or_create_kws(expl_words, req, db)

                db.session.commit()

        return render_template('index.html',
                               status=status,
                               key=key,
                               veredict=veredict,
                               expl_words=expl_words,
                               label=label,
                               ws_on=ws_on,
                               url=url)

    @app.route('/prepare')
    def prepare():
        """
        Creates an intermediate page that prepares the classification answer to be presented. Returns an redirection to the main page.
        """
        socket = context.socket(zmq.REQ)
        socket.connect(
            'tcp://*****:*****@sockets.route('/answer')
    def send_data(ws):
        """
        Establishes a socjet connection with the server to receive status from classification and redirects to prepare page when the result is received.
        """
        print('Got a websocket connection, sending up data from zmq')
        socket = context.socket(zmq.REQ)
        socket.connect(
            'tcp://localhost:{PORT}'.format(PORT=ZMQ_LISTENING_PORT))
        gevent.sleep()

        while True:
            socket.send_string("send status")
            received = socket.recv()
            print("received to socket: ", received)

            data = json.loads(received.decode('utf-8'))

            ws.send(json.dumps(data))
            if data['status'] == "formulating answer" or data[
                    'status'] == 'error':
                break
            gevent.sleep()

    return app, db
コード例 #18
0
ファイル: web_agent.py プロジェクト: tosca07/python-mchess
    def __init__(self, appque, prefs):
        self.name = 'WebAgent'
        self.prefs = prefs
        self.log = logging.getLogger("WebAgent")
        self.appque = appque
        self.orientation = True
        self.active = False
        self.max_plies = 6

        self.display_cache = ""
        self.last_cursor_up = 0
        self.move_cache = ""
        self.info_cache = ""
        self.info_provider = {}
        self.agent_state_cache = {}
        self.uci_engines_cache = {}
        self.display_move_cache = {}
        self.valid_moves_cache = {}
        self.game_stats_cache = {}
        self.max_mpv = 1
        self.last_board = None
        self.last_attribs = None
        self.last_pgn = None

        if 'port' in self.prefs:
            self.port = self.prefs['port']
        else:
            self.port = 8001
            self.log.warning(f'Port not configured, defaulting to {self.port}')

        if 'bind_address' in self.prefs:
            self.bind_address = self.prefs['bind_address']
        else:
            self.bind_address = 'localhost'
            self.log.warning(
                f'Bind_address not configured, defaulting to f{self.bind_address}, set to "0.0.0.0" for remote accessibility'
            )

        self.private_key = None
        self.public_key = None
        if 'tls' in self.prefs and self.prefs['tls'] is True:
            if 'private_key' not in self.prefs or 'public_key' not in self.prefs:
                self.log.error(
                    f"Cannot configure tls without public_key and private_key configured!"
                )
            else:
                self.private_key = prefs['private_key']
                self.public_key = prefs['public_key']

        self.figrep = {
            "int": [1, 2, 3, 4, 5, 6, 0, -1, -2, -3, -4, -5, -6],
            "pythc": [(chess.PAWN, chess.WHITE), (chess.KNIGHT, chess.WHITE),
                      (chess.BISHOP, chess.WHITE), (chess.ROOK, chess.WHITE),
                      (chess.QUEEN, chess.WHITE), (chess.KING, chess.WHITE),
                      (chess.PAWN, chess.BLACK), (chess.KNIGHT, chess.BLACK),
                      (chess.BISHOP, chess.BLACK), (chess.ROOK, chess.BLACK),
                      (chess.QUEEN, chess.BLACK), (chess.KING, chess.BLACK)],
            "unic":
            "♟♞♝♜♛♚ ♙♘♗♖♕♔",
            "ascii":
            "PNBRQK.pnbrqk"
        }
        self.chesssym = {
            "unic": ["-", "×", "†", "‡", "½"],
            "ascii": ["-", "x", "+", "#", "1/2"]
        }

        disable_web_logs = True
        if disable_web_logs is True:
            wlog = logging.getLogger('werkzeug')
            wlog.setLevel(logging.ERROR)
            slog = logging.getLogger('geventwebsocket.handler')
            slog.setLevel(logging.ERROR)
        self.app = Flask(__name__, static_folder='web')
        # self.app.config['ENV'] = "MChess_Agent"
        self.app.config['SECRET_KEY'] = 'secretsauce'
        self.app.debug = False
        self.app.use_reloader = False

        self.sockets = Sockets(self.app)

        self.app.add_url_rule('/node_modules/<path:path>', 'node_modules',
                              self.node_modules)
        self.app.add_url_rule('/', 'root', self.web_root)
        self.app.add_url_rule('/favicon.ico', 'favicon', self.web_favicon)
        self.app.add_url_rule('/index.html', 'index', self.web_root)
        self.app.add_url_rule('/scripts/mchess.js', 'script',
                              self.mchess_script)
        self.app.add_url_rule('/styles/mchess.css', 'style', self.mchess_style)
        self.app.add_url_rule('/images/<path:path>', 'images', self.images)
        self.active = True

        self.sockets.add_url_rule('/ws', 'ws', self.ws_sockets)
        self.ws_clients = {}
        self.ws_handle = 0
        self.log.debug("Initializing web server...")
        self.socket_handler()  # Start threads for web and ws:sockets
コード例 #19
0
def create_app(node_id: str, debug=False, n_replica=None, test_config=None) -> Flask:
    """Create flask application.

    Args:
         node_id: ID used to identify this node.
         debug: debug mode flag.
         n_replica: Number of model replicas used for fault tolerance purposes.
         test_config: database test settings.
    Returns:
         app : Flask App instance.
    """
    app = Flask(__name__)
    app.debug = debug

    app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", None)

    if app.config["SECRET_KEY"] is None:
        app.config["SECRET_KEY"] = DEFAULT_SECRET_KEY
        logging.warning(
            "Using default secrect key, this is not safe and should be used only for testing and development. To define a secrete key please define the environment variable SECRET_KEY."
        )

    app.config["N_REPLICA"] = n_replica
    sockets = Sockets(app)

    # Register app blueprints
    from .main import (
        auth,
        data_centric_routes,
        hook,
        local_worker,
        main_routes,
        model_centric_routes,
        ws,
    )

    # set_node_id(id)
    local_worker.id = node_id
    hook.local_worker._known_workers[node_id] = local_worker
    local_worker.add_worker(hook.local_worker)

    # Register app blueprints
    app.register_blueprint(main_routes, url_prefix=r"/")
    app.register_blueprint(model_centric_routes, url_prefix=r"/model-centric")
    app.register_blueprint(data_centric_routes, url_prefix=r"/data-centric")

    sockets.register_blueprint(ws, url_prefix=r"/")

    # Set SQLAlchemy configs
    set_database_config(app, test_config=test_config)
    s = app.app_context().push()

    if database_exists(db.engine.url):
        db.create_all()
    else:
        db.create_all()
        seed_db()

    db.session.commit()

    # Set Authentication configs
    app = auth.set_auth_configs(app)

    CORS(app)

    # Threads
    executor.init_app(app)
    app.config["EXECUTOR_PROPAGATE_EXCEPTIONS"] = True
    app.config["EXECUTOR_TYPE"] = "thread"

    return app
コード例 #20
0
#     https://cloud.google.com/appengine/docs/flexible/python/using-websockets-and-session-affinity
#     git clone https://github.com/GoogleCloudPlatform/python-docs-samples


from flask         import Flask, request, render_template, redirect, url_for
from flask_sockets import Sockets

import MySQLdb
import private_no_share_dangerous_passwords as pnsdp

import utils



app       = Flask(__name__)
ws_server = Sockets(app)



# connect to the database
def open_db():
    return MySQLdb.connect(host   = pnsdp.SQL_HOST,
                           user   = pnsdp.SQL_USER,
                           passwd = pnsdp.SQL_PASSWD,
                           db     = pnsdp.SQL_DB)



@app.route("/login")
def login():
    return ""
コード例 #21
0
def create_app(handle, instance, reloader=None):
    check.inst_param(handle, 'handle', ExecutionTargetHandle)
    check.inst_param(instance, 'instance', DagsterInstance)
    check.opt_inst_param(reloader, 'reloader', Reloader)

    app = Flask('dagster-ui')
    sockets = Sockets(app)
    app.app_protocol = lambda environ_path_info: 'graphql-ws'

    schema = create_schema()
    subscription_server = DagsterSubscriptionServer(schema=schema)

    execution_manager_settings = instance.dagit_settings.get(
        'execution_manager')
    if execution_manager_settings and execution_manager_settings.get(
            'max_concurrent_runs'):
        execution_manager = QueueingSubprocessExecutionManager(
            instance, execution_manager_settings.get('max_concurrent_runs'))
    else:
        execution_manager = SubprocessExecutionManager(instance)

    warn_if_compute_logs_disabled()

    print('Loading repository...')
    context = DagsterGraphQLContext(
        handle=handle,
        instance=instance,
        execution_manager=execution_manager,
        reloader=reloader,
        version=__version__,
    )

    # Automatically initialize scheduler everytime Dagit loads
    scheduler_handle = context.scheduler_handle
    if scheduler_handle:
        handle = context.get_handle()

        python_path = sys.executable
        repository_path = handle.data.repository_yaml
        scheduler_handle.up(python_path, repository_path)

    app.add_url_rule(
        '/graphql',
        'graphql',
        DagsterGraphQLView.as_view(
            'graphql',
            schema=schema,
            graphiql=True,
            # XXX(freiksenet): Pass proper ws url
            graphiql_template=PLAYGROUND_TEMPLATE,
            executor=Executor(),
            context=context,
        ),
    )
    sockets.add_url_rule(
        '/graphql', 'graphql',
        dagster_graphql_subscription_view(subscription_server, context))

    app.add_url_rule(
        # should match the `build_local_download_url`
        '/download/<string:run_id>/<string:step_key>/<string:file_type>',
        'download_view',
        download_view(context),
    )

    # these routes are specifically for the Dagit UI and are not part of the graphql
    # API that we want other people to consume, so they're separate for now.
    # Also grabbing the magic global request args dict so that notebook_view is testable
    app.add_url_rule('/dagit/notebook', 'notebook',
                     lambda: notebook_view(request.args))

    app.add_url_rule('/static/<path:path>/<string:file>', 'static_view',
                     static_view)
    app.add_url_rule('/vendor/<path:path>/<string:file>', 'vendor_view',
                     vendor_view)
    app.add_url_rule('/<string:worker_name>.worker.js', 'worker_view',
                     worker_view)
    app.add_url_rule('/dagit_info', 'sanity_view', info_view)
    app.add_url_rule('/<path:_path>', 'index_catchall', index_view)
    app.add_url_rule('/', 'index', index_view, defaults={'_path': ''})

    CORS(app)

    return app
コード例 #22
0
ファイル: node.py プロジェクト: stoic-signs/PySyft
def create_domain_app(app, args, testing=False):
    test_config = None

    if args.start_local_db:
        test_config = {"SQLALCHEMY_DATABASE_URI": "sqlite:///nodedatabase.db"}

    # Bind websocket in Flask app instance
    sockets = Sockets(app)

    # Register HTTP blueprints
    # Here you should add all the blueprints related to HTTP routes.
    app.register_blueprint(roles_blueprint, url_prefix=r"/roles")
    app.register_blueprint(users_blueprint, url_prefix=r"/users")
    app.register_blueprint(setup_blueprint, url_prefix=r"/setup")
    app.register_blueprint(groups_blueprint, url_prefix=r"/groups")
    app.register_blueprint(dcfl_blueprint, url_prefix=r"/data-centric/")
    app.register_blueprint(mcfl_blueprint, url_prefix=r"/model-centric/")
    app.register_blueprint(root_blueprint, url_prefix=r"/")
    app.register_blueprint(association_requests_blueprint,
                           url_prefix=r"/association-requests/")

    # Register WebSocket blueprints
    # Here you should add all the blueprints related to WebSocket routes.
    sockets.register_blueprint(ws, url_prefix=r"/")

    # grid relative
    from .database import Role
    from .database import SetupConfig
    from .database import User
    from .database import db
    from .database import seed_db
    from .database import set_database_config

    global node
    node = GridDomain(name=args.name)

    # Set SQLAlchemy configs
    set_database_config(app, test_config=test_config)
    app.app_context().push()
    db.create_all()

    if not testing:
        if len(db.session.query(Role).all()) == 0:
            seed_db()

        if len(db.session.query(SetupConfig).all()) != 0:
            node.name = db.session.query(SetupConfig).first().domain_name

        role = db.session.query(Role.id).filter_by(name="Owner").first()
        user = User.query.filter_by(role=role.id).first()
        if user:
            signing_key = SigningKey(user.private_key.encode("utf-8"),
                                     encoder=HexEncoder)
            node.signing_key = signing_key
            node.verify_key = node.signing_key.verify_key
            node.root_verify_key = node.verify_key

        # Register global middlewares
        # Always after context is pushed
        app.wsgi_app = SleepyUntilConfigured(app, app.wsgi_app)
    db.session.commit()

    app.config["EXECUTOR_PROPAGATE_EXCEPTIONS"] = True
    app.config["EXECUTOR_TYPE"] = "thread"
    executor.init_app(app)

    return app
コード例 #23
0
    """
    print("app logger is called '{}'".format(get_logger_name(app.logger)))
    print("EFF LEVEL {}".format(l.getEffectiveLevel()))
    print("LL is {}".format(l))
    l.debug("debug level")
    l.info("info level")
    l.warn("warn level")
    l.error("error level")
    l.critical("critical level")


logging.config.dictConfig(serverconfig.read_logging_config('logging.yaml'))
the_main = None
app = flask.Flask(__name__.split('.')[0])
test_logging(app.logger)
socky = Sockets(app)
# app.logger.debug('hoity toity')


def gen_arglst() -> typing.List[str]:
    modtt = ('io', )
    retlst = []
    retlst.append('.iv -x')
    numvar = len(modtt)
    numcase = 2**numvar
    oodct = {True: 'on', False: 'off'}
    cmdstr1 = '.iv -al off -e on -r on -ie on -o 29'
    for icase in range(numcase):
        mask = 1
        cmdstropt = ''
        for bit in range(numvar):
コード例 #24
0
ファイル: web_app.py プロジェクト: zr777/kaoqinHelper
import sqlite3
import datetime
import settings

app = Flask(__name__)
app.secret_key = settings.KEY
app.date = None

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"

db = Lab_DB(db_path=settings.DATABASE)
db.init_app(app)

sockets = Sockets(app)  # plus socket
Q = Queue()

infos = settings.INFOS
zhuguan = settings.ZHUGUAN
table = settings.EMAIL_TABLE
template = Template(table)
user_db = settings.ADMINS
# 初始status为全员都到:(主管统一签到)
status = {}
# 初始status为全员都未到且原因未知:(自己签到) # 不方便使用defaultdict
status = {name: '原因' for i in infos for name in i['names']}


# ----------------- 用户及登录 (----------------- #
class User(UserMixin):
コード例 #25
0
from flask import Flask, render_template, request
from flask_sockets import Sockets
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
from sonoff.websocketsrv import WebSocketSrv
from sonoff.websockclient import Websocketclient
from config.config import Config
import json
import requests
import threading

import sonoff.wsclientglb

flaskapp = Flask(__name__)
socket = Sockets(flaskapp)


@flaskapp.route('/')
def home():
    return render_template('main.html')


@flaskapp.route('/dispatch/device', methods=['GET'])
def sonoffDispatchDeviceGet():
    print(
        "REST: Relay attempts to get websocket serever address from GET /dispatch/device"
    )
    jsonresult = {"error": 0, "reason": "ok", "IP": "192.168.1.2", "port": 443}
    return json.dumps(jsonresult)

コード例 #26
0
ファイル: runplugin.py プロジェクト: he0x/rekall
    def PlugManageDocument(cls, app):
        sockets = Sockets(app)

        @sockets.route("/rekall/document/upload")
        def upload_document(ws):  # pylint: disable=unused-variable
            cells = json.loads(ws.receive())
            if not cells:
                return

            worksheet = app.config['worksheet']
            new_data = worksheet.Encoder(cells)
            old_data = worksheet.GetData("notebook_cells", raw=True)
            if old_data != new_data:
                worksheet.StoreData("notebook_cells", new_data, raw=True)

        @app.route("/worksheet/load_nodes")
        def rekall_load_nodes():  # pylint: disable=unused-variable
            worksheet = app.config["worksheet"]
            cells = worksheet.GetData("notebook_cells") or []
            result = dict(filename=worksheet.location,
                          sessions=worksheet.GetSessionsAsJson(),
                          cells=cells)

            return json.dumps(result), 200

        @app.route("/worksheet/load_file")
        def load_new_worksheet():  # pylint: disable=unused-variable
            session = app.config['worksheet'].session
            worksheet_dir = session.GetParameter("notebook_dir", ".")
            path = os.path.normpath(request.args.get("path", ""))
            full_path = os.path.join(worksheet_dir, "./" + path)

            # First check that this is a valid Rekall file.
            try:
                fd = io_manager.ZipFileManager(full_path, mode="a")
                if not fd.GetData("notebook_cells"):
                    raise IOError
            except IOError:
                return "File is not a valid Rekall File.", 500

            old_worksheet = app.config["worksheet"]
            old_worksheet.Close()

            app.config["worksheet"] = fd

            return "Worksheet is updated", 200

        @app.route("/worksheet/save_file")
        def save_current_worksheet():  # pylint: disable=unused-variable
            """Save the current worksheet into worksheet directory."""
            worksheet = app.config['worksheet']
            session = app.config['worksheet'].session
            worksheet_dir = session.GetParameter("notebook_dir", ".")
            path = os.path.normpath(request.args.get("path", ""))
            full_path = os.path.join(worksheet_dir, "./" + path)

            with open(full_path, "wb") as out_zip:
                with zipfile.ZipFile(
                        out_zip, mode="w",
                        compression=zipfile.ZIP_DEFLATED) as out_fd:
                    cells = worksheet.GetData("notebook_cells") or []
                    out_fd.writestr("notebook_cells", json.dumps(cells))

                    for cell in cells:
                        # Copy all the files under this cell id:
                        path = "%s/" % cell["id"]
                        for filename in worksheet.ListFiles():
                            if filename.startswith(path):
                                with worksheet.Open(filename) as in_fd:
                                    # Limit reading to a reasonable size (10Mb).
                                    out_fd.writestr(filename,
                                                    in_fd.read(100000000))

            worksheet.Close()

            app.config["worksheet"] = io_manager.ZipFileManager(full_path,
                                                                mode="a")

            return "Worksheet is saved", 200

        @app.route("/worksheet/list_files")
        def list_files_in_worksheet_dir():  # pylint: disable=unused-variable
            worksheet = app.config['worksheet']
            session = worksheet.session

            try:
                worksheet_dir = os.path.abspath(worksheet.location or ".")
                full_path = os.path.abspath(
                    os.path.join(worksheet_dir, request.args.get("path", "")))

                if not os.path.isdir(full_path):
                    full_path = os.path.dirname(full_path)

                result = []
                for filename in sorted(os.listdir(full_path)):
                    if filename.startswith("."):
                        continue

                    file_stat = os.stat(os.path.join(full_path, filename))
                    file_type = "file"
                    if stat.S_ISDIR(file_stat.st_mode):
                        file_type = "directory"

                    full_file_path = os.path.join(full_path, filename)

                    # If the path is within the worksheet - make it relative to
                    # the worksheet.
                    relative_file_path = os.path.relpath(
                        full_file_path, worksheet_dir)

                    if not relative_file_path.startswith(".."):
                        full_file_path = relative_file_path

                    result.append(
                        dict(name=filename,
                             path=full_file_path,
                             type=file_type,
                             size=file_stat.st_size))

                # If the path is within the worksheet - make it relative
                # to the worksheet.
                relative_path = os.path.relpath(full_path, worksheet_dir)
                if not relative_path.startswith(".."):
                    full_path = relative_path

                return jsonify(files=result, path=full_path)
            except (IOError, OSError) as e:
                return str(e), 500

        @app.route("/uploads/worksheet", methods=["POST"])
        def upload_new_worksheet():  # pylint: disable=unused-variable
            """Replace worksheet with uploaded file."""
            worksheet = app.config['worksheet']
            session = app.config['worksheet'].session
            worksheet_dir = session.GetParameter("notebook_dir", ".")

            for in_fd in request.files.itervalues():
                path = os.path.normpath(in_fd.filename)
                full_path = os.path.join(worksheet_dir, "./" + path)

                with open(full_path, "wb") as out_fd:
                    utils.CopyFDs(in_fd, out_fd)

            return "OK", 200

        @app.route("/downloads/worksheet")
        def download_worksheet():  # pylint: disable=unused-variable
            worksheet = app.config["worksheet"]
            data = cStringIO.StringIO()
            with zipfile.ZipFile(data,
                                 mode="w",
                                 compression=zipfile.ZIP_DEFLATED) as out_fd:
                cells = worksheet.GetData("notebook_cells") or []
                out_fd.writestr("notebook_cells", json.dumps(cells))

                for cell in cells:
                    # Copy all the files under this cell id:
                    path = "%s/" % cell["id"]
                    for filename in worksheet.ListFiles():
                        if filename.startswith(path):
                            with worksheet.Open(filename) as in_fd:
                                # Limit reading to a reasonable size (10Mb).
                                out_fd.writestr(filename,
                                                in_fd.read(100000000))

            return data.getvalue(), 200, {
                "content-type": 'binary/octet-stream',
                'content-disposition': "attachment; filename='rekall_file.zip'"
            }
コード例 #27
0
    app = Flask(__name__)
    app.secret_key = 'feca0226-1746-6666-92ac-1999e1eea085'

    @app.route('/')
    def index():
        return 'The flexx app is under the flexx folder: <a href="/flexx/">your.server.com/flexx</a>'

    @app.route('/stop')
    def stop():
        global server
        server.stop()
        return 'stopping'

    ########### Register apps ###########
    app.register_blueprint(FlexxBlueprint, url_prefix='/flexx')
    ########### Register sockets ###########
    sockets = Sockets(app)  # keep at the end
    sockets.register_blueprint(FlexxWS, url_prefix='/flexx')

    # from gevent import monkey; monkey.patch_all() # moved at beginning
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    import platform

    server = pywsgi.WSGIServer(('127.0.0.1', 5000),
                               app,
                               handler_class=WebSocketHandler)
    print("Server Started!")
    server.serve_forever()
コード例 #28
0
ファイル: runplugin.py プロジェクト: he0x/rekall
    def PlugRunPluginsIntoApp(cls, app):
        sockets = Sockets(app)
        thread_pool = threadpool.ThreadPool(5)

        @app.route("/rekall/runplugin/cancel/<cell_id>", methods=["POST"])
        def cancel_execution(cell_id):  # pylint: disable=unused-variable
            worksheet = app.config["worksheet"]
            # Signal the worksheet to abort this cell.
            worksheet.aborted_cells.add(int(cell_id))

            return "OK", 200

        @sockets.route("/rekall/runplugin")
        def rekall_run_plugin_socket(ws):  # pylint: disable=unused-variable
            cell = json.loads(ws.receive())
            cell_id = cell["cell_id"]
            source = cell["source"]
            worksheet = app.config["worksheet"]

            # If the data is cached locally just return it.
            cache_key = GenerateCacheKey(source)
            cache = worksheet.GetData("%s.data" % cell_id)
            if cache and cache.get("cache_key") == cache_key:
                logging.debug("Dumping request from cache")
                ws.send(json.dumps(cache.get("data")))
                return

            kwargs = source.get("arguments", {})

            # Must provide the correct session to run this on.
            session_id = int(source.pop("session_id"))
            session = worksheet.session.find_session(session_id)

            output = cStringIO.StringIO()
            output_queue = Queue.Queue()
            renderer = WebConsoleRenderer(session=session,
                                          output=output,
                                          cell_id=cell_id,
                                          output_queue=output_queue,
                                          worksheet=worksheet)

            # Clear the interruption state of this cell.
            worksheet.aborted_cells.discard(cell_id)

            def RunPlugin():
                with renderer.start():
                    try:
                        session.RunPlugin(source["plugin"]["name"],
                                          renderer=renderer,
                                          **kwargs)

                    except Exception:
                        message = traceback.format_exc()
                        renderer.report_error(message)

            run_plugin_result = thread_pool.spawn(RunPlugin)

            sent_messages = []

            def HandleSentMessages():
                while not run_plugin_result.ready() or not output_queue.empty(
                ):
                    while not output_queue.empty():
                        message = output_queue.get()
                        sent_messages.append(message)
                        ws.send(
                            json.dumps([message],
                                       cls=json_renderer.RobustEncoder))
                    run_plugin_result.wait(0.1)

            handle_messages_thread = gevent.spawn(HandleSentMessages)

            gevent.joinall([run_plugin_result, handle_messages_thread])

            # Cache the data in the worksheet.
            worksheet.StoreData("%s.data" % cell_id,
                                dict(cache_key=cache_key, data=sent_messages))
コード例 #29
0
from flask import Flask
from flask_sockets import Sockets
import random
import time
import thread

ws_handlers = []
app = Flask(__name__)
sockets = Sockets(app)


@sockets.route('/location')
def echo_socket(ws):
    global ws_handlers
    print "connected!"
    ws_handlers = [1]
    ws_handlers[0] = ws

    print 'len connected ', len(ws_handlers)
    while not ws.closed:
        message = ws.receive()
        print "receive:", message

    print 'sockets disconnected!'
    ws_handlers = []


def genData():
    global ws_handlers
    while 1:
        if len(ws_handlers) > 0:
コード例 #30
0
    def app_protocol(self, unused) -> str:
        """This method is called by geventwebsocket (handler.py) in order to set the
        websocket protocol.
        The name of the method is significant (it must be called exactly this)
        The websocket protocol must be defined, or the server will not respond correctly
        (missing Sec-WebSocket-Protocol entry in the response header)
        and this will crash the stocky webclient when it is run under chrome.
        NOTE: the websocket protocol is hardcoded to be 'json' on the webclient side.
        """
        return 'json'


logging.config.dictConfig(serverconfig.read_logging_config('logging.yaml'))
app: typing.Optional[stockyapp] = stockyapp()
socky: typing.Optional[Sockets] = Sockets(app)
the_main: typing.Optional[stockyserver.CommonStockyServer] = None


def initRFIDserver(cfgname: str) -> flask.Flask:
    """This routine is used as a helper in order to launch the StockyServer class with the
    name of a configuration file, e.g. in a launching shell script, such as runserver.sh,
    we would write something like:
    gunicorn -k flask_sockets.worker "stocky:init_app('scoconfig.yaml')" --bind 0.0.0.0:5000
    """
    print("hello from init_RFIDserver")
    global the_main
    # test_logging(app.logger)
    the_main = stockyserver.StockyRFIDServer(app.logger, cfgname, commlink.SerialCommLink)
    # logging.config.dictConfig(serverconfig.read_logging_config('logging.yaml'))
    print("goodbye from init_RFIDserver")