示例#1
0
 def post(self):
     hash = self.request.body[:32]
     j = self.request.body[32:]
     m = md5(j + config.SENDCOMMAND_SECRET)
     if m.hexdigest() == hash:
         c = json.loads(j)
         serverinfo.ServerInfo.send_command(c['info'],
                                            json.dumps(c['command']))
         if config.is_debug():
             self.response.headers['Content-Type'] = 'text/plain'
             self.response.out.write('ok')
     else:
         if config.is_debug():
             self.response.headers['Content-Type'] = 'text/plain'
             self.response.out.write('not ok')
示例#2
0
 def post(self):
     hash = self.request.body[:32]
     j = self.request.body[32:]
     m = md5(j + config.SENDCOMMAND_SECRET)
     if m.hexdigest() == hash:
         c = json.loads(j)
         serverinfo.ServerInfo.send_command(c['info'],
                 json.dumps(c['command']))
         if config.is_debug():
             self.response.headers['Content-Type'] = 'text/plain'
             self.response.out.write('ok')
     else:
         if config.is_debug():
             self.response.headers['Content-Type'] = 'text/plain'
             self.response.out.write('not ok')
示例#3
0
def register_endpoints(app):
    """
    Registers all the endpoints used by the frontend to deliver the index.html in all cases.
    :param app: the flask app
    """
    @app.route("/", methods=["GET"])
    def get_index():
        """
        Each call to the API, which doesn't start with `/api` will be covered by this function providing the index.html
        to the caller. The index.html will load the index.js in the browser, which will render the frontend. The
        frontend will then decide what view to render. The backend is not responsible for that.

        **IMPORTANT**
        This function needs to be updated whenever new frontend routes are added to the React router. You can provide
        multiple @app.route(..) lines for multiple frontend routes that all just return the frontend (because the
        frontend has it's own router which decides what page to render)

        :return: the index.html as file (basically delivering the whole frontend)
        """
        return render_template("index.html")

    # prevent caching of the frontend during development
    if is_debug():

        @app.after_request
        def add_header(r):
            """
            Add headers to both force latest IE rendering engine or Chrome Frame,
            and also to cache the rendered page for 10 minutes.
            """
            r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
            r.headers["Pragma"] = "no-cache"
            r.headers["Expires"] = "0"
            r.headers['Cache-Control'] = 'public, max-age=0'
            return r
示例#4
0
    def post(self):
        # Update server info
        j = self.request.body[32:]
        info = self.validate_request()
        if not info:
            if config.is_debug():
                self.response.set_status(400, 'not valid')
            return

        # Update the model.
        key = models.serverinfomodel_key(info['name'], info['start_utc'])
        obj = models.ServerInfoModel.get(key)
        if not obj:
            obj = models.ServerInfoModel(key_name=key.name())

        # Save the command
        command = obj.command

        obj.json = j
        obj.command = ''
        obj.expires_utc = info['expires_utc']
        obj.put()

        # Update the cache now rather than just invalidating, so the latency
        # isn't on a client request
        self.gen_json()

        # Return command if there is one
        if command:
            # Use this mime type for simplicity, and so GAE doesn't strip
            # out Content-Length
            self.response.headers['Content-Type'] = 'binary/octet-stream'
            self.response.headers['Content-Length'] = len(command)
            self.response.out.write(command)
示例#5
0
def main():
    handlers = [
            (config.ADDGAMESTATS_URL, addgamestats.AddGameStats),
            (config.AUTH_URL, auth.AuthUser),
            (config.LEADERBOARD_URL, leaderboard.Leaderboard),
            (config.AVATAR_URL, avatar.AvatarHandler),
            (config.STATS_URL, stats.Stats),
            (config.GAMES_URL, games.Games),
            (config.SEARCH_URL, search.Search),
            (config.ABOUT_URL, about.About),
            (config.GAMEDETAIL_URL, gamedetail.GameDetail),
            (config.MESSAGE_URL, message.Message),
            (config.CREATEACCOUNT_URL, createaccount.CreateAccount),
            (config.UPDATEACCOUNT_URL, updateaccount.UpdateAccount),
            (config.SERVERINFO_URL, serverinfo.ServerInfo),
            (config.SYNCERROR_URL, syncerror.SyncError),
            (config.ADMIN_URL, admin.Admin),
            (config.SENDCHAT_URL, sendchat.SendChat),
            (config.DRAIN_URL, drain.Drain),
            (config.SENDCOMMAND_URL, sendcommand.SendCommand),
            (config.BLOCKPLAYER_URL, blockplayer.BlockPlayer),
            (config.HIDEPLAYER_URL, hideplayer.HidePlayer),
            (config.RESETPLAYER_URL, resetplayer.ResetPlayer),
            (config.RATINGJOB_URL, ratingjob.RatingJob),
            (config.GETGAMES_URL, getgames.GetGames),
            (config.PLAYERDETAIL_URL, playerdetail.PlayerDetail),
            (config.ADJUSTSCORE_URL, adjustscore.AdjustScore),
            (config.ADMINLOG_URL, adminlog.AdminLog),
    ]
    application = webapp.WSGIApplication(handlers, debug=config.is_debug())
    run_wsgi_app(application)
示例#6
0
    def post(self):
        # Update server info
        j = self.request.body[32:]
        info = self.validate_request()
        if not info:
            if config.is_debug():
                self.response.set_status(400, 'not valid')
            return

        # Update the model.
        key = models.serverinfomodel_key(info['name'], info['start_utc'])
        obj = models.ServerInfoModel.get(key)
        if not obj:
            obj = models.ServerInfoModel(key_name=key.name())

        # Save the command
        command = obj.command

        obj.json = j
        obj.command = ''
        obj.expires_utc = info['expires_utc']
        obj.put()

        # Update the cache now rather than just invalidating, so the latency
        # isn't on a client request
        self.gen_json()

        # Return command if there is one
        if command:
            # Use this mime type for simplicity, and so GAE doesn't strip
            # out Content-Length
            self.response.headers['Content-Type'] = 'binary/octet-stream'
            self.response.headers['Content-Length'] = len(command)
            self.response.out.write(command)
示例#7
0
def main():
    handlers = [
        (config.ADDGAMESTATS_URL, addgamestats.AddGameStats),
        (config.AUTH_URL, auth.AuthUser),
        (config.LEADERBOARD_URL, leaderboard.Leaderboard),
        (config.AVATAR_URL, avatar.AvatarHandler),
        (config.STATS_URL, stats.Stats),
        (config.GAMES_URL, games.Games),
        (config.SEARCH_URL, search.Search),
        (config.ABOUT_URL, about.About),
        (config.GAMEDETAIL_URL, gamedetail.GameDetail),
        (config.MESSAGE_URL, message.Message),
        (config.CREATEACCOUNT_URL, createaccount.CreateAccount),
        (config.UPDATEACCOUNT_URL, updateaccount.UpdateAccount),
        (config.SERVERINFO_URL, serverinfo.ServerInfo),
        (config.SYNCERROR_URL, syncerror.SyncError),
        (config.ADMIN_URL, admin.Admin),
        (config.SENDCHAT_URL, sendchat.SendChat),
        (config.DRAIN_URL, drain.Drain),
        (config.SENDCOMMAND_URL, sendcommand.SendCommand),
        (config.BLOCKPLAYER_URL, blockplayer.BlockPlayer),
        (config.HIDEPLAYER_URL, hideplayer.HidePlayer),
        (config.RESETPLAYER_URL, resetplayer.ResetPlayer),
        (config.RATINGJOB_URL, ratingjob.RatingJob),
        (config.GETGAMES_URL, getgames.GetGames),
        (config.PLAYERDETAIL_URL, playerdetail.PlayerDetail),
        (config.ADJUSTSCORE_URL, adjustscore.AdjustScore),
        (config.ADMINLOG_URL, adminlog.AdminLog),
    ]
    application = webapp.WSGIApplication(handlers, debug=config.is_debug())
    run_wsgi_app(application)
示例#8
0
def main():
    # initializing pygame
    pygame.init()
    pygame.mixer.init()
    pygame.font.init()

    # setting up the game window
    resolution = config.get_resolution()
    win = pygame.display.set_mode(resolution)
    pygame.display.set_caption("Tudo que entra, também sai")
    pygame.display.set_icon(load_image(images.TOILET_ICON))
    clock = pygame.time.Clock()

    # scenes dictionary, to ease the access
    router = {
        START_SCENE: StartScene(win),
        GAME_SCENE: None,
        GAME_OVER_SCENE: GameOverScene(win),
        HOW_TO_PLAY_SCENE: HowToPlayScene(win),
        CREDITS_SCENE: CreditsScene(win)
    }

    # current scene being rendered
    current_scene = router[config.get(config.STARTING_SCENE) or START_SCENE]

    prev_command = None
    command = None

    while 1:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                sys.exit()
            elif config.is_debug() and event.type == pygame.MOUSEBUTTONDOWN:
                print(pygame.mouse.get_pos())

        prev_command = command

        # renders a scene and receives a command from it
        if prev_command is not None:
            command = current_scene.render(
                events=events, more_args=prev_command.get('more_args'))
        else:
            command = current_scene.render(events=events)

        # when the previous command is not the game scene, it means we're starting a new game scene
        starting_at_game_scene = prev_command is None and command[
            'goto'] == GAME_SCENE
        moving_to_game_scene = prev_command is not None and prev_command[
            'goto'] != GAME_SCENE and command['goto'] == GAME_SCENE
        if starting_at_game_scene or moving_to_game_scene:
            router[GAME_SCENE] = GameScene(win)

        # the command contains a goto action indicating the next scene to be rendered
        current_scene = router[command['goto']]

        pygame.display.update()
        clock.tick(40)
示例#9
0
from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from config import initialize_config, is_debug
from os import environ

initialize_config()

Base = declarative_base()
engine = create_engine('postgresql://{DBUSER}:{DBPASS}@{DBSERVER}:{DBPORT}/{DBNAME}'.format(**environ),
                       echo=is_debug())

song_chord = Table('song_chord', Base.metadata,
                   Column('song_id', Integer, ForeignKey('song.id'), index=True),
                   Column('chord_id', Integer, ForeignKey('chord.id'), index=True)
)


class Song(Base):
    __tablename__ = 'song'
    id = Column(Integer(), primary_key=True, nullable=False, autoincrement=True)
    artist = Column(String(length=200))
    name = Column(String(length=200), nullable=False)
    url = Column(String(length=200), nullable=False, unique=True, index=True)
    rating = Column(Integer())
    created_date = Column(DateTime(), nullable=False, index=True)
    chords = relationship('Chord', secondary=song_chord, backref='songs', lazy='joined')

    def __str__(self):
        return '"{0}" by {1}'.format(self.name, self.artist)
示例#10
0
        _, line = line.split('\t', 1)
    except ValueError:
        continue
    segs = [s.strip() for s in line.split('\05')]
    if len(segs) < NUM or not segs[ADSL]:
        continue

    info.adsl = segs[ADSL]
    # DOMAIN 字段实际为host
    info.host = segs[HOST]
    info.raw_url = segs[URL]
    # 对URL进行urllib2.decode解码,将其中的%转码过的信息还原为原始字符串
    info.url = trans_str(info.raw_url)

    info.url = utility.spider_url_to_dpi_url(info.url)
    info.domain = utility.host_to_domain(info.host)

    if config.is_debug():
        print u"test" + u",".join(
            [info.adsl, info.url, info.host, info.domain])

    label_id = set()
    update_label_id(info.url, label_id)
    update_label_id(info.refer, label_id)

    if len(label_id) > 0:
        try:
            print u"\t".join([info.adsl, u",".join(label_id)])
        except UnicodeEncodeError:
            pass
示例#11
0
                             logout_user, login_required)
from flask_oauthlib.client import OAuth
from utils.formutils import write_errors_to_flash
from utils.templatehelpers import url_for_lang, lang_name, get_translation
from utils.data import get_measurement_data
from utils.impersonation import ImpersonationContext


def get_send_file_max_age(self, name):
    return 31449600


Flask.get_send_file_max_age = get_send_file_max_age

app = Flask(__name__)
app.config['COMPRESS_DEBUG'] = is_debug()
app.config['ASSETS_DEBUG'] = is_debug()
app.jinja_env.globals['now'] = datetime.utcnow()
app.jinja_env.globals['periods'] = PERIODS
app.jinja_env.globals['url_for_lang'] = url_for_lang
app.jinja_env.globals['lang_name'] = lang_name
app.jinja_env.globals['get_translation'] = get_translation
app.jinja_env.globals['LANGUAGES'] = LANGUAGES
app.jinja_env.globals['ADMIN_USER'] = environ['ADMIN_USER']
app.jinja_env.globals['impersonation_context'] = ImpersonationContext()
app.secret_key = environ['APPSECRET']

login_manager = LoginManager(app)
login_manager.login_view = 'login'

oauth = OAuth()
示例#12
0
# -*- coding: utf-8 -*-

import argparse
import locale

import tornado.ioloop
import tornado.web

import config
from config import AppConfig
import routes

# date of release; run fab timestamp to set it
__date__ = "2012-03-01 19:02:03+0000"
__version__ = "1"

if __name__ == '__main__':
    args_parser = argparse.ArgumentParser()
    args_parser.add_argument("-p", "--port", type=int)
    clargs = vars(args_parser.parse_args())
    port = clargs["port"]
    if port is None:
        port = 8000

    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
    application = tornado.web.Application(routes.all,
                                          cookie_secret=AppConfig.default().cookie_secret,
                                          debug=config.is_debug())
    application.listen(port, xheaders=True)
    tornado.ioloop.IOLoop.instance().start()
示例#13
0
        ContentStore(mongo_url=mongo_url,
                     mongo_db=mongo_db,
                     collection_name="content"),
    }

    # create flask app
    app = Flask(__name__)
    # register endpoints
    static_api.register_endpoints(app)
    # register endpoints for authentication and user management
    register_user_endpoints(app, stores["user"], stores["user_tokens"])
    # register endpoints for data management and retrieval
    register_data_endpoints(
        app,
        stores["data"],
        {
            "manage_permission":
            "data",  # permission required to manage content
            "login_check_function":
            check_login_state,  # this function ties the authentication module into this one
        })
    # register endpoints for content management
    register_content_endpoints(
        app, stores["content"], {
            "manage_permission": "content",
            "login_check_function": check_login_state,
        })

    # start flask app
    app.run(host='0.0.0.0', port=get_port(), debug=is_debug())
示例#14
0
def debug(message):
    """ Only logs message if its debug mode """

    if config.is_debug():
        print(message)
示例#15
0
from models.Subscription import Item
from config import database_name, user_collection
from billing.stripe import stripe
from starlette.responses import RedirectResponse
from config import MAIN_URL
from auth.oauth2 import oauth2_scheme, verify_token
from errors.auth import credentials_exception
from errors.billing import payment_system_exception
from models.User import UserInfo
from dependencies import find_user
from core.Plan import get_tier
from config import is_debug, COUPON_ID

router = APIRouter(prefix="/billing",
                   tags=["billing-route"],
                   include_in_schema=is_debug())


class BillingURL:
    success = MAIN_URL + "/#success"
    plans_page = MAIN_URL + "/plans"
    sign_up_page = MAIN_URL + "/join"


@router.post(
    "/session", )
async def billing_session(
        plan: Item,
        token: UserInfo = Depends(oauth2_scheme),
        db: AsyncIOMotorClient = Depends(get_database),
):
示例#16
0
from binance.enums import SIDE_BUY, SIDE_SELL, ORDER_TYPE_MARKET
from binance.exceptions import BinanceAPIException, BinanceOrderException

import binance_client
import binance_sockets
import config
import tickers
import log

# CONFIGS
BINANCE_MAX_PRECISION = config.get('binance_max_precision')
MARKETS = config.get('markets')
ORDER_VALUE = config.get('order_value')
MIN_SPREAD = config.get('min_spread')
TEST_MODE = config.is_test()
DEBUG_MODE = config.is_debug()

# CONSTS
LIST_LIMIT = 5
FEE = 0.05

# Tracking variables
start_time = datetime.now()
arbitrages_count = 0
reverse_arbitrages_count = 0
check_count = 0

# General exchange info
exchanges = []

SYMBOLS = [
示例#17
0

@app.route('/chord_filter', methods=['GET'])
def chord_filter():
    q = request.args.get('q')
    r = [c for c in _get_all_chords() if c['name'].lower().startswith(q.lower())] if q else []
    return jsonify(results=r)


@app.route('/search', methods=['GET'])
def search():
    results, chords, total_count, elapsed = _search(request.args.get('q'),
                                                    list(map(int, request.args.get('crd', '').split(','))) if request.args.get('crd', '') else [],
                                                    _get_current_page(),
                                                    request.args.get('s'))
    page_data = {
        'query': request.args.get('q'),
        'chord_names': ', '.join([c['name'] for c in chords]) if chords else '',
        'selected_chords': chords,
        'results': results,
        'total_count': total_count,
        'elapsed': elapsed,
        'pagination': Pagination(_get_current_page(), PAGE_SIZE, total_count),
        'stats': _get_stats()
    }
    return render_template('search_results.html', **page_data)


if __name__ == '__main__':
    app.run(debug=is_debug(), use_reloader=False)
示例#18
0
from fastapi import APIRouter, Depends, status
from fastapi.responses import JSONResponse

from models.User import UserInfo, UpdateUser
from errors.auth import credentials_exception
from db.mongodb import AsyncIOMotorClient, get_database
from config import database_name, user_collection, is_debug
from auth.oauth2 import (
    oauth2_scheme,
    verify_token,
)

router = APIRouter(prefix="/user", include_in_schema=is_debug())


@router.get("/", tags=["user"])
async def get_current_user(
        token: UserInfo = Depends(oauth2_scheme),
        db: AsyncIOMotorClient = Depends(get_database),
):
    if token:
        id = verify_token(token)
    else:
        raise credentials_exception
    if (user := await db[database_name]
        [user_collection].find_one({"_id": id}, {
            "_id": False,
            "hashed_password": False
        })) is not None:
        return user
    raise credentials_exception
示例#19
0
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.add_event_handler("startup", connect_to_mongo)
app.add_event_handler("shutdown", close_mongo_connection)

app.include_router(users.router, prefix=API_V1_STR)
app.include_router(matches.router, prefix=API_V1_STR)
app.include_router(auth.router, prefix=API_V1_STR)
app.include_router(billing.router)
app.include_router(webhooks.webhooks, prefix=API_V1_STR)
app.include_router(model_stats.router, prefix=API_V1_STR)

app.include_router(plans.router)

if __name__ == "__main__":
    print("DEBUG", is_debug())
    print("Database URI ", MONGO_URI)
    print("Database: ", MONGO_DB)
    print("ALLOWED_HOSTS: ", ALLOWED_HOSTS)

    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        log_level="info",
        reload=is_debug(),
    )