예제 #1
0
 def build_app_init(self, config={}, **limiter_args):
     app = Sanic(__name__)
     for k, v in config.items():
         app.config.setdefault(k, v)
     limiter_args.setdefault('key_func', get_remote_address)
     limiter = Limiter(**limiter_args)
     limiter.init_app(app)
     mock_handler = mock.Mock()
     mock_handler.level = logging.INFO
     limiter.logger.addHandler(mock_handler)
     return app, limiter
예제 #2
0
def setup_rate_limiter(app: Sanic):
    limiter = Limiter(
        app,
        global_limits=["1000/hour", "100/second"],
        key_func=get_remote_address,
        strategy="moving-window",
        storage_uri="memory://",
    )

    return limiter
예제 #3
0
from sanic import Sanic, response, exceptions
from sanic_cors import CORS, cross_origin
from sanic_limiter import Limiter, get_remote_address
import argparse, json, logging, os, sys

# Setup
app = Sanic()
CORS(app)
limiter = Limiter(app, key_func=get_remote_address)

logger = logging.getLogger()
config = {}

# Utils


def debug(msg):
    if config['debug'] == True:
        logger.info(msg)


# Routes


@app.route("/1", methods=['GET'])
@limiter.limit("")
async def test1(request):
    try:
        if (request.args["text"]):
            return response.text("Valid request")
    except:
예제 #4
0
    if loaded is None:
        loaded = {}
    # Replace default options with ones provided in the file
    config = {**config, **loaded}
app.update_config(config)
logger.info("Config loaded.")

jwt = sanic_jwt.Initialize(
    app,
    authenticate=auth.authenticate(app),
    secret=config["AUTH_SECRET"],
    url_prefix=config["AUTH_URL_PREFIX"],
    expiration_delta=config["AUTH_EXPIRATION_DELTA"],
)
limiter = Limiter(app,
                  global_limits=["120/minute"],
                  key_func=get_remote_address)
# TODO: Make this optionally enabled
CORS(app)

INDEX_PAGE = str(Path.cwd() / "ui" / "build" / "index.html")
app.static("/", INDEX_PAGE)
app.static("/start-survey/", INDEX_PAGE)
app.static("/complete/", INDEX_PAGE)


@app.route("/survey/<_n>")
async def survey(_request, _n):
    return await response.file(INDEX_PAGE)

예제 #5
0
# demo start
from sanic import Sanic, Blueprint
from sanic.response import text

from sanic_limiter import Limiter, get_remote_address

app = Sanic(__name__)
limiter = Limiter(app, global_limits=['1 per hour', '10 per day'], key_func=get_remote_address)
bp = Blueprint('some_bp')
limiter.limit("2 per hour")(bp)


@bp.route("/bp1")
async def bp_t1(request):
    return text("bp_t1")


@app.route("/t1")
@limiter.limit("100 per hour;10/minute")
async def t1(request):
    return text("t1")


@app.route("/t2")
async def t2(request):
    return text("t2")


@app.route("/t3")
@limiter.exempt
async def t3(request):
예제 #6
0
파일: app.py 프로젝트: cykreet/getV
from sanic import Sanic
from sanic.response import json

from sanic_limiter import Limiter, get_remote_address
from bs4 import BeautifulSoup


async def ratelimit_handler(request, exception):
    return json({"error": f"Ratelimit exceeded {exception}."}, status=429)


app = Sanic()
app.error_handler.add(Exception, ratelimit_handler)

limiter = Limiter(app,
                  global_limits=["1 per 3 seconds", "50 per hour"],
                  key_func=get_remote_address)


@app.route("/")
async def main(request):
    if not (bot := request.args.get("bot")):
        return json({"error": "Bot query is required. Example: ?bot=atlas"})

    soup = BeautifulSoup((response :=
                          requests.get(f"https://top.gg/bot/{bot}")).content,
                         "html.parser")

    if (status := response.status_code) not in [200, 204]:
        return json({
            "status": status,
예제 #7
0
#!/usr/bin/env python3

from sanic_prometheus import monitor
from sanic import Sanic, response, Blueprint
from sanic_limiter import Limiter, get_remote_address

app = Sanic()
test_bp = Blueprint('test')

limiter = Limiter(app,
                  global_limits=['10 per second', '500 per day'],
                  key_func=get_remote_address)


@test_bp.route('/home', methods=['GET'])
async def home(request):
    return response.json({'success': 'you are home'})


if __name__ == '__main__':
    monitor(app).expose_endpoint()
    app.blueprint(test_bp)
    app.run(host='127.0.0.1',
            port=8000,
            auto_reload=False,
            access_log=True,
            debug=True)
예제 #8
0
from sanic import Sanic
from sanic import response
from aiocache import cached
from aiohttp import ClientSession, ClientConnectorError
from sanic_limiter import Limiter, get_remote_address

app = Sanic('cyesec')
limiter = Limiter(app)


async def fetch_data_from_remote_server(session, url):
    try:
        async with session.get(url) as result:
            return await result.json()
    except ClientConnectorError as e:
        return ('Connection Error', str(e))


@cached(ttl=3600)
async def expensive_request_should_use_cache(get_remote_address):
    url = "https://reqres.in/api/users"
    async with ClientSession() as session:
        result = await fetch_data_from_remote_server(session, url)
        return response.json(result)


@app.route("/")
@limiter.limit("1000 per day;10/minute", key_func=get_remote_address)
async def handle_request(request):
    return await expensive_request_should_use_cache(get_remote_address)
예제 #9
0
파일: __init__.py 프로젝트: yc19890920/ap
app.config.update(settings.SANIC_REDIS_CONFIG)
app.config.LOGO = settings.LOGO.format(', Y.c')
# app.config.LOGO = None

app.blueprint(openapi_blueprint)
app.blueprint(swagger_blueprint)

redis = SanicRedis(app)
CORS(app, automatic_options=True)

app.blueprint(crud_bp)
# 接口访问限制
# app.config.RATELIMIT_STORAGE_URL = 'redis://127.0.0.1:6379'
limiter = Limiter(app,
                  global_limits=['10000 per hour', '100000 per day'],
                  key_func=get_remote_address,
                  # storage_uri='redis://localhost:6379/1'
                  )
limiter.init_app(app)
limiter.limit("1000 per hour")(crud_bp)
# limiter.exempt(crud_bp)


# JWT 配置
# jwt 返回jwt 获取token的键设置,将改变默认键 access_token
app.config.SANIC_JWT_ACCESS_TOKEN_NAME = 'sanic-token'
# app.config.SANIC_JWT_ACCESS_TOKEN_NAME = 'jwt'

# 设置过期时间, 默认30分钟
# app.config['JWT_EXPIRATION_DELTA'] = datetime.timedelta(days=10)
app.config['JWT_EXPIRATION_DELTA'] = datetime.timedelta(seconds=60)
def getLimiter(app):
    return Limiter(app,
                   global_limits=['5 per minute'],
                   key_func=get_remote_address)
예제 #11
0
app = Sanic('Ember For Test Automation')
app.blueprint(swagger_blueprint)
app.config.from_object(get_config())
bcrypt = Bcrypt(app)

if development:
    # CORS(app)
    # app.config['CORS_SUPPORTS_CREDENTIALS'] = True
    sio = socketio.AsyncServer(async_mode='sanic', cors_allowed_origins='*')
else:
    sio = socketio.AsyncServer(async_mode='sanic')
sio.attach(app)

limits = ['20000 per hour', '200000 per day'
          ] if development else ['200 per hour', '2000 per day']
limiter = Limiter(app, global_limits=limits, key_func=get_remote_address)
event_task = None
heartbeat_task = None
rpc_server = None
db_client = None


@app.listener('before_server_start')
async def setup_connection(app, loop):
    global event_task, heartbeat_task, rpc_server, db_client

    db_client = motor.motor_asyncio.AsyncIOMotorClient(
        f"{app.config['MONGODB_URL']}:{app.config['MONGODB_PORT']}")
    app.config.db = db_client[app.config['MONGODB_DATABASE']]

    from task_runner.runner import initialize_runner, start_event_thread, start_heartbeat_thread, start_xmlrpc_server
예제 #12
0
from sanic import Sanic, Blueprint
from referral.blueprints.user import user_bp
from sanic.response import json
from sanic_cors import CORS, cross_origin
from sanic_limiter import Limiter, get_remote_address
# from refer_file import add_user_with_filters, go_through_network
from sanic.response import text
from sanic.exceptions import NotFound, SanicException

import sys

app = Sanic(__name__)
CORS(app, automatic_options=True)

limiter = Limiter(app, global_limits=['100 per hour', '40 per minute'])

# app.static('/', './referral/static')
# app.static('/', './referral/static/index.html')
app.blueprint(user_bp)


@app.exception(NotFound)
async def ignore_404s(request, exception):
    return text("Yep, I totally found the page: {}".format(request.url))


@app.exception(SanicException)
async def sanic_except(request, exception):
    return text("HAHAHAHAH: {}".format(request.url))