text stringlengths 0 1.05M | meta dict |
|---|---|
from functools import wraps
from flask import \
render_template, redirect, url_for, \
abort, flash, request, current_app, \
make_response
from flask_login import \
login_required, current_user, \
login_user, logout_user
from sqlalchemy.orm import lazyload
from datetime import date, datetime, timedelta, time
from calendar import Calendar
from urllib.parse import quote
from .models import *
from .forms import *
################################################################################
print('Initializing views')
# fix_month_year :: Month -> Year -> (Month, Year)
def fix_month_year(m, y):
while m > 12:
m -= 12
y += 1
while m < 1:
m += 12
y -= 1
return (m, y)
# Returns the date of the first day of the next month
def get_next_month(this_month):
(m, y) = fix_month_year(this_month.month + 1, this_month.year)
return date(y, m, 1)
# Returns the date of the first day of the prev month
def get_prev_month(this_month):
(m, y) = fix_month_year(this_month.month - 1, this_month.year)
return date(y, m, 1)
#TODO fix validity checker
valid_paths = ['/', '/login', '/logout', '/register']
def next_is_valid(next):
for i in valid_paths:
if next == i:
return True
return False
def logout_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if current_user.is_anonymous:
return f(*args, **kwargs)
return redirect(url_for('calendar_route'))
return decorated_function
def parse_date_from_args(args):
today = date.today()
try:
s_year = int(request.args.get('year') or today.year)
s_month = int(request.args.get('month') or today.month)
s_day = int(request.args.get('day') or today.day)
return date(s_year, s_month, s_day)
except:
return today
################################################################################
# / redirects to calendar
@current_app.route('/')
def root():
return redirect(url_for('calendar_route'))
################################################################################
# Login form
# Get request displays a login-form
# Post checks user credentials and loggs in the user, redirects to calendar
@current_app.route('/login', methods=['GET', 'POST'])
@logout_required
def login_route():
form = LoginForm()
if form.validate_on_submit():
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username).first()
if user is None or not user.verify_password(password):
flash('Invalid username/password pair')
return render_template('login.html', title='Sign In', form=form)
login_user(user)
flash('Logged in as {}'.format(username))
next = request.args.get('next')
if next_is_valid(next):
return redirect(next)
return redirect(url_for('calendar_route'))
return render_template('login.html', title='Sign In', form=form)
################################################################################
# Loggs out the user
# Redirects to calendar
@current_app.route('/logout')
@login_required
def logout_route():
logout_user()
flash('Logged out')
return redirect(url_for('calendar_route'))
################################################################################
# On GET displays a register new user form
# On post checks if the username is already taken
# Adds a user-entry and redirects to login
@current_app.route('/register', methods=['GET','POST'])
@logout_required
def register_route():
form = RegisterForm()
if form.validate_on_submit():
username = request.form['username']
pw = request.form['password']
pw_retype = request.form['retype_password']
same_count = User.query.filter_by(username=username).count()
if same_count != 0:
flash('Username {} already taken'.format(username))
elif pw != pw_retype:
flash('Passwords do not match')
else:
new_user = User(username, pw)
db.session.add(new_user)
db.session.commit()
flash('Successfully registered')
return redirect(url_for('login_route'))
return render_template('register.html', title='Register', form=form)
################################################################################
# get_month_events :: Year -> Month -> [[Day]]
# type Day = (Date, [Event])
def get_month_events(year, month):
# Get the day-dates of the current month
cal = Calendar(0) # default replace by user db? (starting day)
the_month = cal.monthdatescalendar(year, month)
# First day of first week
begin = the_month[0][0]
# Last day of last week
end = the_month[-1][-1]
events = Event.query.filter(
Event.event_date > begin.strftime('%Y-%m-%d'),
Event.event_date < end.strftime('%Y-%m-%d')) \
.options(lazyload('creator')).all()
# Load the days for the calendar
def per_day(day):
# Get the interval bounds of that day
day_start = datetime.combine(day, time())
day_end = day_start + timedelta(days = 1)
# Run through all events
day_events = []
for e in events:
if e.event_date >= day_start and e.event_date < day_end:
day_events.append(e)
return (day, day_events)
def per_week(week):
return [per_day(d) for d in week]
def per_month(month):
return [per_week(w) for w in month]
return per_month(the_month)
# Load the event ids of all your subscribed events.
# Anon users are not subscribed to anything.
def get_subscribed_event_ids():
if not current_user.is_anonymous:
your_subscriptions = db.session.query(Subscription.event_id) \
.filter(Subscription.user_id == current_user.id).all()
return [x for (x,) in your_subscriptions]
return []
# Returns a list of the next #limit events.
# If only_yours is True, only your events are listed.
# If start_date is None, today is chosen.
# If end_date is set, only events up to that date are queried.
def get_next_events(limit, start_date = None, end_date = None, only_yours = True):
# Load the events for the event sidebar
start_date = start_date or datetime.today()
query = db.session.query(Event)
if only_yours and not current_user.is_anonymous:
query = query.join(Subscription) \
.filter(Subscription.user_id == current_user.id)
query = query.filter(Event.event_date > start_date)
if end_date:
query = query.filter(Event.event_date < end_date)
query = query \
.options(lazyload('creator')) \
.order_by(Event.event_date)
if limit:
query = query.limit(limit)
return query.all()
# get_day_events :: [Event]
def get_day_events(year, month, day):
today = date(year,month,day)
tomorrow = today + timedelta(days=1)
events = Event.query.filter(
Event.event_date > today.strftime('%Y-%m-%d'),
Event.event_date < tomorrow.strftime('%Y-%m-%d')).all()
return events
################################################################################
# Route to subscribe for events. Requires the 'subscribe'-field.
# If the current user is not already subscriber for that event, a subscription
# with 'Yes' and an empty comment is added.
# This route redirects to the submitted 'next' address, or back to the calendar-view.
@current_app.route('/subscribe', methods=['POST'])
@login_required
def subscribe_route():
subscribe = request.form.get('subscribe')
if subscribe is not None:
# Integrity checks
optionally_redundant_subscriptions = Subscription.query\
.filter(Subscription.event_id == int(subscribe))\
.filter(Subscription.user_id == current_user.id).all()
if not optionally_redundant_subscriptions:
s = Subscription(current_user.id, int(subscribe))
db.session.add(s)
db.session.commit()
flash('Subscribed to event')
else:
flash('Already subscribed to that event')
next = request.form.get('next') or url_for('calendar_route')
return redirect(next)
################################################################################
# displays the calendar.
# If year and month are submitted, displays a month view
# If the day is also submitted displays a day-view
@current_app.route('/calendar', methods=['GET'])
def calendar_route():
now = date.today()
year = int(request.args.get('year') or now.year)
month = int(request.args.get('month') or now.month)
day = request.args.get('day')
# Get the current (localized) month name.
at_month = date(year, month, 1)
month_name = at_month.strftime("%B")
# Month view
if day is None:
day_events = get_month_events(year, month)
your_subscriptions = get_subscribed_event_ids()
next_events = get_next_events(limit = 5)
return render_template(
'calendar_month.html',
title='Calendar',
day_events = day_events,
your_subscriptions = your_subscriptions,
next_events = next_events,
month_name=month_name)
# Day view
day = int(day)
day_and_events = get_day_events(year, month, day)
#day_and_events = [(e,e.creator) for e in day_and_events]
return render_template(
'calendar_day.html',
title='Calendar',
year=year,
month=month,
day=day,
month_name=month_name,
this_path=quote(request.path),
day_and_events=day_and_events)
################################################################################
# Route for /event
# Handles GET requests, which display the event. Event owners are presented with an edit form
# Right side of this view contains the list of subscribers, which can edit their own subscriptions.
@current_app.route('/event', methods=['GET'])
def event_route():
event_id = request.args.get('id')
if event_id is None:
flash('Event id required for "/event"')
return redirect(url_for('calendar_route'))
event = Event.query.filter(Event.id == event_id).first()
if event is None:
flash('Event with id ' + event_id + ' not found')
return redirect(url_for('calendar_route'))
# Helper function to create a subscription_form on the fly.
def make_subscription_form(subscr):
subscr_form = SubscriptionForm()
subscr_form.subscriptionid.data = subscr.id
subscr_form.comment.data = subscr.comment
subscr_form.commitment.data = subscr.commitment
return subscr_form
event_form = EditForm()
event_form.id.data = event.id
event_form.name.data = event.name
event_form.date.data = event.event_date.date()
event_form.time.data = event.event_date.time()
event_form.description.data = event.description
# Additional fields
event_form.timeleft = event.remaining_time
event_form.creatorid = event.creator_id
cuser_is_subscribed = False
if not current_user.is_anonymous:
current_user_suscribed = Subscription.query \
.filter(Subscription.event_id == event.id) \
.filter(Subscription.user_id == current_user.id).first()
cuser_is_subscribed = not current_user_suscribed is None
return render_template(
'event.html',
title = 'Event',
is_subscribed = cuser_is_subscribed,
subscriptions = event.subscriptions,
make_subscription_form = make_subscription_form,
event_form = event_form)
################################################################################
# Handles POST requests, which are used to edit the event.
# Redirects to /event?id={{request.form['eventid']}}
@current_app.route('/edit_event', methods=['POST'])
def edit_event_route():
id = request.form['id']
event_form = EditForm()
if event_form.validate_on_submit():
event = Event.query.filter(Event.id == int(id)).one()
if event.creator_id == current_user.id:
event.name = request.form['name']
date = event_form.date.data
time = event_form.time.data
event.event_date = datetime.combine(date, time)
event.description = request.form['description']
db.session.commit()
flash('Event updated')
else:
flash('You cannot edit this event')
return redirect(url_for('event_route', id=id))
################################################################################
@current_app.route('/edit_subscription', methods=['POST'])
def edit_subscription_route():
form = SubscriptionForm()
if form.validate_on_submit():
subscription = Subscription.query \
.filter(Subscription.id == request.form.get('subscriptionid')) \
.options(lazyload('user')) \
.options(lazyload('event')).one()
subscription.comment = request.form.get('comment')
subscription.commitment = request.form.get('commitment')
db.session.commit()
flash('Subscription updated')
return redirect(url_for('event_route', id=subscription.event_id))
################################################################################
@current_app.route('/subscriptions', methods=['GET'])
@login_required
def subscriptions_route():
# events = current_user.subscriptions
events = db.session.query(Event).join(Subscription) \
.filter(Subscription.user_id==current_user.id) \
.order_by(Event.event_date).all()
return render_template(
'subscriptions.html',
title='Your subscriptions',
events=events)
################################################################################
# The get request may contain a predefined year, month, day.
# If these parameters are omitted, the current ones are chosen.
@current_app.route('/add', methods=['GET', 'POST'])
@login_required
def add_route():
form = EventForm()
if form.validate_on_submit():
event_name = request.form['name']
date = form.date.data
time = form.time.data
event_date = datetime.combine(date, time)
event_descr = request.form['description']
e = Event(event_date, event_name, event_descr, current_user.id)
db.session.add(e)
db.session.commit()
s = Subscription(current_user.id, e.id)
db.session.add(s)
db.session.commit()
return redirect(url_for('event_route', id=e.id))
form.date.data = parse_date_from_args(request.args)
#form.time.data = parse_date_from_args(request.args)
return render_template(
'add_event.html',
form=form,
title='Add Event')
################################################################################
@current_app.route('/<other>', methods=['GET', 'POST'])
def not_found(other = None):
flash('Invalid path: {}'.format(other))
return redirect(url_for('calendar_route'))
################################################################################
"""
# Returns the localized month name
# Assuming date(2016, month, 1) returns the first day of month=month
def month_to_name(month):
at_month = date(2016, month, 1)
return at_month.strftime("%B")
# Returns a list of weeks where each week contains a list of days
# Hardcoding Monday to be the first day of the week
def date_to_weeks(year, month):
start_date = date(year, month, 1)
day_of_week = start_date.weekday()
one_day = timedelta(1)
start_date -= day_of_week * one_day
weeks = []
while start_date.month <= month:
week = []
for i in range(0,7):
week.append(start_date.strftime("%A"))
start_date += one_day
weeks.append(week)
return weeks
# Can be performed once! TODO
# Returns a list of localized weekday names
# Hardcoding Monday to be the first day of the week
def week_to_days():
now = date.today()
one_day = timedelta(1)
monday = now - now.weekday() * one_day
weekdays = []
for i in range(0,7):
weekdays.append((monday + timedelta(i)).strftime("%A"))
return weekdays
"""
| {
"repo_name": "alexd2580/evelyn",
"path": "evelyn/views.py",
"copies": "1",
"size": "16334",
"license": "mit",
"hash": -592651581599556900,
"line_mean": 33.7531914894,
"line_max": 99,
"alpha_frac": 0.5884045549,
"autogenerated": false,
"ratio": 3.946363856003866,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.003862155341451675,
"num_lines": 470
} |
from functools import wraps
from flask import redirect, session, url_for, flash, render_template
# Decorator to require log in
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if "logged_in" in session:
return f(*args, **kwargs)
else:
flash("not logged in")
return redirect(url_for("login"))
return wrap
# Decorator to lock log in page after logged in
def no_login(f):
@wraps(f)
def wrap(*args, **kwargs):
if "logged_in" not in session:
return f(*args, **kwargs)
else:
flash("You are already logged in.")
return redirect(url_for("index"))
return wrap
# Decorator to allow only users "julian" and "admin" to certain pages
def admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if session["username"] == "julian" or session["username"] == "admin":
return f(*args, **kwargs)
else:
return render_template("no_permission.html", subheading="", page="exempt")
return wrap
| {
"repo_name": "naliuj/WHHB-Twitter-Bot",
"path": "user_management/page_restrictions.py",
"copies": "1",
"size": "1067",
"license": "mit",
"hash": -1753373738998964700,
"line_mean": 27.8378378378,
"line_max": 86,
"alpha_frac": 0.5932521087,
"autogenerated": false,
"ratio": 3.937269372693727,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00031065548306927616,
"num_lines": 37
} |
from functools import wraps
from flask import redirect, url_for
from flask.ext.login import current_user
from models import *
import re
from unicodedata import normalize
import bbcode
def get_current_user_role():
user = User.query.filter_by(email=current_user.email).first()
roles = []
for role in user.roles:
roles.append(role.name)
return roles
def accepted_roles(*roles):
def wrapper(f):
@wraps(f)
def wrapped(*args, **kwargs):
user_roles = get_current_user_role()
permission = False
for role in user_roles:
if role in roles:
permission = True
if not permission:
return redirect(url_for('permission_denied'))
return f(*args, **kwargs)
return wrapped
return wrapper
# Slugify
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
def slugify(text, delim=u'-'):
"""Generates an slightly worse ASCII-only slug."""
result = []
for word in _punct_re.split(text.lower()):
word = normalize('NFKD', word).encode('ascii', 'ignore')
if word:
result.append(word)
return unicode(delim.join(result))
# BBCode Parser
def dev(tag_name, value, options, parent, context):
return '<div class="dev">%s</div>' % value
def html(tag_name, value, options, parent, context):
return value
def article_img(tag_name, value, options, parent, context):
return '<div class="article_image"><img src="%s" /></div>' % value
def pre(tag_name, value, options, parent, context):
return '<pre class="prettyprint">%s</pre>' % value
def code(tag_name, value, options, parent, context):
return '<code class="prettyprint">%s</code>' % value
bbparser = bbcode.Parser()
bbparser.add_formatter('dev',
dev,
strip=True,
swallow_trailing_newline=True)
bbparser.add_formatter('html',
html,
escape_html=False,
swallow_trailing_newline=True,
transform_newlines=False,
replace_links=False,
replace_cosmetic=False)
bbparser.add_formatter('article_img',
article_img,
replace_links=False,
swallow_trailing_newline=True)
bbparser.add_formatter('pre',
pre)
bbparser.add_formatter('code',
code)
bbparser.add_simple_formatter('h1', '<h1>%(value)s</h1>')
bbparser.add_simple_formatter('h2', '<h2>%(value)s</h2>')
bbparser.add_simple_formatter('h3', '<h3>%(value)s</h3>')
bbparser.add_simple_formatter('h4', '<h4>%(value)s</h4>')
| {
"repo_name": "VincentTide/vincenttide",
"path": "app/utility.py",
"copies": "1",
"size": "2755",
"license": "mit",
"hash": -5929056492946702000,
"line_mean": 30.6666666667,
"line_max": 70,
"alpha_frac": 0.5720508167,
"autogenerated": false,
"ratio": 3.8052486187845305,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9871213725744865,
"avg_score": 0.0012171419479329736,
"num_lines": 87
} |
from functools import wraps
from flask import redirect, url_for
from urlobject import URLObject
from requests_oauthlib import OAuth1Session as BaseOAuth1Session
from requests_oauthlib import OAuth2Session as BaseOAuth2Session
from oauthlib.common import to_unicode
from werkzeug.utils import cached_property
from flask_dance.utils import invalidate_cached_property
class OAuth1Session(BaseOAuth1Session):
"""
A :class:`requests.Session` subclass that can do some special things:
* lazy-loads OAuth1 tokens from the storage via the blueprint
* handles OAuth1 authentication
(from :class:`requests_oauthlib.OAuth1Session` superclass)
* has a ``base_url`` property used for relative URL resolution
Note that this is a session between the consumer (your website) and the
provider (e.g. Twitter), and *not* a session between a user of your website
and your website.
"""
def __init__(self, blueprint=None, base_url=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.blueprint = blueprint
self.base_url = URLObject(base_url)
@cached_property
def token(self):
"""
Get and set the values in the OAuth token, structured as a dictionary.
"""
return self.blueprint.token
def load_token(self):
t = self.token
if t and "oauth_token" in t and "oauth_token_secret" in t:
# This really, really violates the Law of Demeter, but
# I don't see a better way to set these parameters. :(
self.auth.client.resource_owner_key = to_unicode(t["oauth_token"])
self.auth.client.resource_owner_secret = to_unicode(t["oauth_token_secret"])
return True
return False
@property
def authorized(self):
"""This is the property used when you have a statement in your code
that reads "if <provider>.authorized:", e.g. "if twitter.authorized:".
The way it works is kind of complicated: this function just tries
to load the token, and then the 'super()' statement basically just
tests if the token exists (see BaseOAuth1Session.authorized).
To load the token, it calls the load_token() function within this class,
which in turn checks the 'token' property of this class (another
function), which in turn checks the 'token' property of the blueprint
(see base.py), which calls 'storage.get()' to actually try to load
the token from the cache/db (see the 'get()' function in
storage/sqla.py).
"""
self.load_token()
return super().authorized
@property
def authorization_required(self):
"""
.. versionadded:: 1.3.0
This is a decorator for a view function. If the current user does not
have an OAuth token, then they will be redirected to the
:meth:`~flask_dance.consumer.oauth1.OAuth1ConsumerBlueprint.login`
view to obtain one.
"""
def wrapper(func):
@wraps(func)
def check_authorization(*args, **kwargs):
if not self.authorized:
endpoint = f"{self.blueprint.name}.login"
return redirect(url_for(endpoint))
return func(*args, **kwargs)
return check_authorization
return wrapper
def prepare_request(self, request):
if self.base_url:
request.url = self.base_url.relative(request.url)
return super().prepare_request(request)
def request(
self, method, url, data=None, headers=None, should_load_token=True, **kwargs
):
if should_load_token:
self.load_token()
return super().request(
method=method, url=url, data=data, headers=headers, **kwargs
)
class OAuth2Session(BaseOAuth2Session):
"""
A :class:`requests.Session` subclass that can do some special things:
* lazy-loads OAuth2 tokens from the storage via the blueprint
* handles OAuth2 authentication
(from :class:`requests_oauthlib.OAuth2Session` superclass)
* has a ``base_url`` property used for relative URL resolution
Note that this is a session between the consumer (your website) and the
provider (e.g. Twitter), and *not* a session between a user of your website
and your website.
"""
def __init__(self, blueprint=None, base_url=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.blueprint = blueprint
self.base_url = URLObject(base_url)
invalidate_cached_property(self, "token")
@cached_property
def token(self):
"""
Get and set the values in the OAuth token, structured as a dictionary.
"""
return self.blueprint.token
def load_token(self):
self._client.token = self.token
if self.token:
self._client.populate_token_attributes(self.token)
return True
return False
@property
def access_token(self):
"""
Returns the ``access_token`` from the OAuth token.
"""
return self.token and self.token.get("access_token")
@property
def authorized(self):
"""This is the property used when you have a statement in your code
that reads "if <provider>.authorized:", e.g. "if twitter.authorized:".
The way it works is kind of complicated: this function just tries
to load the token, and then the 'super()' statement basically just
tests if the token exists (see BaseOAuth1Session.authorized).
To load the token, it calls the load_token() function within this class,
which in turn checks the 'token' property of this class (another
function), which in turn checks the 'token' property of the blueprint
(see base.py), which calls 'storage.get()' to actually try to load
the token from the cache/db (see the 'get()' function in
storage/sqla.py).
"""
self.load_token()
return super().authorized
@property
def authorization_required(self):
"""
.. versionadded:: 1.3.0
This is a decorator for a view function. If the current user does not
have an OAuth token, then they will be redirected to the
:meth:`~flask_dance.consumer.oauth2.OAuth2ConsumerBlueprint.login`
view to obtain one.
"""
def wrapper(func):
@wraps(func)
def check_authorization(*args, **kwargs):
if not self.authorized:
endpoint = f"{self.blueprint.name}.login"
return redirect(url_for(endpoint))
return func(*args, **kwargs)
return check_authorization
return wrapper
def request(self, method, url, data=None, headers=None, **kwargs):
if self.base_url:
url = self.base_url.relative(url)
self.load_token()
return super().request(
method=method,
url=url,
data=data,
headers=headers,
client_id=self.blueprint.client_id,
client_secret=self.blueprint.client_secret,
**kwargs,
)
| {
"repo_name": "singingwolfboy/flask-dance",
"path": "flask_dance/consumer/requests.py",
"copies": "1",
"size": "7241",
"license": "mit",
"hash": -452918958073882000,
"line_mean": 35.205,
"line_max": 88,
"alpha_frac": 0.6276757354,
"autogenerated": false,
"ratio": 4.372584541062802,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5500260276462802,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import render_template, flash, redirect, url_for, request, g
from flask.ext.login import login_user, logout_user, current_user, login_required
from app import app, db, lm, rc
from forms import LoginForm, SignupForm, CreateGameForm, JoinGameForm
from wtforms.ext.sqlalchemy.orm import model_form
from flask_wtf import Form
from models import User, Game, Deck, Fact, get_object_or_404
from flask.ext.admin.contrib.sqla import ModelView
from game_object import GameObject
@app.before_request
def before_request():
g.user = current_user
@lm.user_loader
def load_user(userid):
return User.query.get(int(userid))
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not g.user.is_admin():
return redirect(url_for('index'))
return f(*args, **kwargs)
return decorated_function
@app.route('/', methods = ['GET', 'POST'])
@app.route('/index', methods = ['GET', 'POST'])
@login_required
def index():
games = Game.query.order_by(Game.id.desc()).limit(20)
create_form = CreateGameForm(g.user)
join_form = JoinGameForm(g.user)
if join_form.validate_on_submit():
game = Game.query.get(join_form.game_id.data)
game.guest_id = g.user.id
game.status = 'joined'
db.session.add(game)
db.session.commit()
go = GameObject().from_game(game)
rc.set("g%d" % game.id, go.to_json())
return redirect(url_for('game', game_id=game.id))
elif create_form.validate_on_submit():
host_player = User.query.get(create_form.user_id.data)
new_game = Game(host_player, deck=create_form.deck.data, reversed=create_form.reversed.data)
db.session.add(new_game)
db.session.commit()
go = GameObject().from_game(new_game)
rc.set("g%d" % new_game.id, go.to_json())
return redirect(url_for('game', game_id=new_game.id))
return render_template(
'index.html',
user=g.user,
create_form=create_form,
page='index',
games=games
)
@app.route('/game/<int:game_id>', methods = ['GET', 'POST'])
@login_required
def game(game_id=None):
game = get_object_or_404(Game, Game.id == game_id)
host_player = None
guest_player = None
if game.status == 'canceled':
return redirect(url_for('index'))
if game.status == 'created':
host_player = get_object_or_404(User, User.id == game.host_id)
if game.status == 'joined':
host_player = get_object_or_404(User, User.id == game.host_id)
guest_player = get_object_or_404(User, User.id == game.guest_id)
role = 'watcher'
if g.user.id == game.host_id:
role = 'host'
elif g.user.id == game.guest_id:
role = 'join'
return render_template(
'game.html',
game=game,
role=role,
host_player=host_player,
guest_player=guest_player,
page='game'
)
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form = SignupForm()
if form.validate_on_submit():
new_user = User(form.username.data, form.email.data, form.password.data)
db.session.add(new_user)
db.session.commit()
login_user(new_user)
return redirect(request.args.get('next') or url_for('index'))
return render_template('signup.html', form=form)
@app.route('/login', methods=['GET', 'POST'])
def login():
if g.user is not None and g.user.is_authenticated():
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
# login and validate the user...
user = User.query.filter_by(username = form.username.data).first()
login_user(user)
flash('Logged in successfully.', category='success')
return redirect(request.args.get('next') or url_for('index'))
return render_template('login.html', form=form)
@app.route('/logout')
@login_required
def logout():
logout_user()
flash('Logged out successfully.', category='success')
return redirect(url_for('index'))
@app.route('/profile', methods = ['GET', 'POST'])
@app.route('/profile/<int:user_id>', methods = ['GET', 'POST'])
@login_required
def profile(user_id = None):
if g.user is not None and g.user.is_authenticated():
if user_id is None:
return render_template('profile.html', user=g.user)
else:
user = User.query.get(user_id)
if user:
return render_template('profile.html', user=user)
else:
return redirect(url_for('index'))
else:
if user_id is None:
return redirect(url_for('index'))
else:
user = User.query.get(user_id)
@app.route('/profile/edit', methods = ['GET', 'POST'])
@login_required
def edit_profile():
if g.user is not None and g.user.is_authenticated():
UserForm = model_form(User, db_session=db.session,
base_class=Form, only=['email', 'name']
)
model = User.query.get(g.user.id)
form = UserForm(request.form, model)
if form.validate_on_submit():
form.populate_obj(model)
db.session.add(model)
db.session.commit()
flash('Profile updated', category='success')
return redirect(url_for('profile'))
return render_template('edit_profile.html', user=g.user, form=form)
else:
return render_template('404.html'), 404
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
# admin pages
class UserView(ModelView):
# Disable model creation
can_create = False
# Override displayed fields
column_list = ('username', 'name', 'email', 'role')
column_filters = ('username', 'name', 'email')
def __init__(self, session, **kwargs):
# You can pass name and other parameters if you want to
super(UserView, self).__init__(User, session, **kwargs)
def is_accessible(self):
return g.user.is_admin()
class DeckView(ModelView):
def __init__(self, session, **kwargs):
# You can pass name and other parameters if you want to
super(DeckView, self).__init__(Deck, session, **kwargs)
def is_accessible(self):
return g.user.is_admin()
class FactView(ModelView):
column_filters = ('front', 'back')
column_list = ('front', 'back', 'decks_used')
def __init__(self, session, **kwargs):
# You can pass name and other parameters if you want to
super(FactView, self).__init__(Fact, session, **kwargs)
def is_accessible(self):
return g.user.is_admin()
| {
"repo_name": "vigov5/pvp-game",
"path": "app/views.py",
"copies": "1",
"size": "6654",
"license": "mit",
"hash": 497848452074567740,
"line_mean": 32.7766497462,
"line_max": 100,
"alpha_frac": 0.6190261497,
"autogenerated": false,
"ratio": 3.4602184087363494,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45792445584363495,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, abort
from flask.views import MethodView
class NamedMethod(object):
def __init__(self, name, http_method_name):
self.name = name
self.http_method_name = http_method_name
def __call__(self, method):
self.method = method
if self.http_method_name is None:
self.http_method_name = method.__name__
self.http_method_name = self.http_method_name.lower()
return self
def namedmethod(name, http_method_name=None):
return NamedMethod(name, http_method_name)
class NamedMethodViewBase(MethodView.__metaclass__):
def __new__(meta, name, bases, members):
members['_namedmethods'] = {}
namedmethods = ((name, namedmethod)\
for (name, namedmethod) \
in members.items() \
if isinstance(namedmethod, NamedMethod))
for name, namedmethod in namedmethods:
if not namedmethod.name in members['_namedmethods']:
members['_namedmethods'][namedmethod.name] = {}
members['_namedmethods']\
[namedmethod.name]\
[namedmethod.http_method_name] = namedmethod.method
if not 'methods' in members:
members['methods'] = []
if not namedmethod.http_method_name in members['methods']:
members['methods'].append(namedmethod.http_method_name)
members = dict(((n,v) for (n,v) in members.items() \
if not isinstance(v, NamedMethod)))
methods = [v.__name__.lower() for (n, v)\
in members.items() \
if callable(v) and v.__name__.lower() in \
('get', 'post', 'put', 'patch', 'head', 'options', 'track', 'update')]
if methods:
if not 'methods' in members:
members['methods'] = []
members['methods'].extend(methods)
return super(NamedMethodViewBase, meta)\
.__new__(meta, name, bases, members)
class NamedMethodView(MethodView):
__metaclass__ = NamedMethodViewBase
__headername__ = 'X-View-Name'
def dispatch_method(self, method, *args, **kwargs):
if method is None and request.method == 'HEAD':
method = getattr(self, 'get', None)
return method(*args, **kwargs)
def get_named_method(self, name):
meth = self._namedmethods.get(name, {}).get(request.method.lower(), None)
if meth is not None:
return meth.__get__(self, self.__class__)
def dispatch_request(self, *args, **kwargs):
if self.__headername__ in request.headers:
method = self.get_named_method(request.headers[self.__headername__])
if method is not None:
return self.dispatch_method(method, *args, **kwargs)
if not hasattr(self, request.method.lower()):
abort(405)
return super(NamedMethodView, self).dispatch_request(*args, **kwargs)
if __name__ == '__main__':
import unittest
from flask import Flask
from pprint import pprint
class TestedNamedView(NamedMethodView):
@namedmethod('editor')
def get(self):
return 'editor get'
@namedmethod('editor', 'post')
def editor_post(self):
return 'editor post'
def post(self):
return 'raw post'
test = Flask(__name__)
test.config['TESTING'] = True
test.config['DEBUG'] = True
test.config['SERVER_NAME'] = 'localhost:5000'
test.add_url_rule('/test', view_func=TestedNamedView.as_view('test'))
class TestNamedMethodView(unittest.TestCase):
def setUp(self):
self.client = test.test_client()
def test_405(self):
self.assertTrue(self.client.get('/test').status_code == 405)
def test_named_get(self):
self.assertTrue(''.join(self.client.get('/test',
headers=[('X-View-Name', 'editor')]).response) == 'editor get')
def test_raw_post(self):
self.assertTrue(''.join(self.client.post('/test').response) == 'raw post')
def test_named_post(self):
self.assertTrue(''.join(self.client.post('/test',
headers=[('X-View-Name', 'editor')]).response) == 'editor post')
unittest.main()
# test.run() | {
"repo_name": "denz/swarm-crawler",
"path": "swarm_crawler/serve/namedview.py",
"copies": "1",
"size": "4412",
"license": "bsd-3-clause",
"hash": 7112835163810690000,
"line_mean": 35.775,
"line_max": 90,
"alpha_frac": 0.569356301,
"autogenerated": false,
"ratio": 4.1195144724556485,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0065062913890575865,
"num_lines": 120
} |
from functools import wraps
from flask import request, abort
import jwt
class SimpleJWT:
"""
Class to manage JWT Token in Flask
"""
def __init__(self, secret, realm=None, algorithms=None):
"""
Class constructor
Initializes the secret key for the token
:param secret: string - JWT Secret key
:param realm: string - Authorization realm. Default Bearer
:param algorithms: strings array - Supported algorithms. Default empty
"""
self.secret = secret
self.realm = realm if realm is not None else 'Bearer'
self.algorithms = algorithms if algorithms is not None else []
def jwt_required(self):
"""
Decorator used to enforce JWT Authentication
on views
:return: function - endpoint secured with JWT
"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not request.headers.has_key('Authorization'):
abort(401, "Authorization required")
auth = request.headers['Authorization'].split()
if len(auth) != 2:
abort(400, "Malformed authorization header")
if auth[0].lower() != self.realm.lower():
abort(401, "Unsupported realm")
try:
jwt.decode(auth[1], self.secret, algorithms=self.algorithms)
except jwt.ExpiredSignatureError:
abort(401, "Signature has expired")
except jwt.DecodeError:
abort(401, "Signature verification failed")
except Exception:
abort(400, "JWT Error")
return f(*args, **kwargs)
return decorated_function
return decorator
def get_jwt_token(self):
"""
Return the encoded JWT token without Realm
:return: string - JWT Token
"""
if not request.headers.has_key('Authorization'):
return ""
auth = request.headers['Authorization'].split()
if len(auth) != 2:
return ""
return auth[1] | {
"repo_name": "depa77/flask-simplejwt",
"path": "flask_simplejwt/flask_simplejwt.py",
"copies": "1",
"size": "2189",
"license": "mit",
"hash": -281970958104429950,
"line_mean": 29.4166666667,
"line_max": 80,
"alpha_frac": 0.5523069895,
"autogenerated": false,
"ratio": 4.952488687782806,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6004795677282806,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, Blueprint, jsonify
from api.errors import *
from api.models import Snippet
api_v1 = Blueprint('v1', __name__)
######################## Authentication ################################
def requires_authentication(func):
@wraps(func)
def wrapper(*args, **kwargs):
pass
return wrapper
############################# Views ####################################
@api_v1.teardown_request
def shutdown_session(exception=None):
db.session.remove()
@api_v1.route('/meta', methods=['GET'])
def index():
data = {
"name": "My API",
"version": "1.0",
"organisation": "Me only",
"description": "this is version 1.0 of my api!"
}
return jsonify(data)
@api_v1.route('/snippets', methods=['POST'])
def save_snippet():
if request.json:
snippet = Snippet(title=request.json['title'],
language=request.json['language'],
code=request.json['snippet'])
db.session.add(snippet)
db.session.commit()
return Response(json.dumps({"id": snippet.id}),
201,
mimetype='application/json')
else:
return not_acceptable('Please ensure that your request contains a valid JSON')
@api_v1.route('/snippets', methods=['GET'])
def get_all_snippets():
data = {}
data['snippets'] = []
snippets = Snippet.query.order_by(Snippet.updated_at)
for snippet in snippets:
data['snippets'].append(snippet.get_dict())
return Response(json.dumps(data),
200,
mimetype='application/json')
@api_v1.route('/snippets/language/<language>', methods=['GET'])
def get_all_snippets_for_language(language):
data = {}
data['snippets'] = []
snippets = Snippet.query.filter_by(language=language).all()
for snippet in snippets:
print snippet.id
data['snippets'].append(snippet.get_dict())
return Response(json.dumps(data),
200,
mimetype='application/json')
@api_v1.route('/snippets/<snippet_id>', methods=['PUT'])
def update_snippet(snippet_id):
if request.json:
snippet = Snippet.query.get(snippet_id)
if snippet:
snippet.update_code(request.json['snippet'])
db.session.add(snippet)
db.session.commit()
return Response(200)
else:
return not_found()
else:
return not_acceptable()
@api_v1.route('/snippets/<snippet_id>', methods=['DELETE'])
def delete_snippet(snippet_id):
snippet = Snippet.query.get(snippet_id)
if snippet:
db.session.delete(snippet)
db.session.commit()
return Response(200)
else:
return not_found()
| {
"repo_name": "kirang89/youten",
"path": "api/v1/views.py",
"copies": "1",
"size": "2823",
"license": "mit",
"hash": -6957500527335435000,
"line_mean": 27.23,
"line_max": 86,
"alpha_frac": 0.5671271697,
"autogenerated": false,
"ratio": 4.03862660944206,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.510575377914206,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, Blueprint, render_template, jsonify, flash, \
redirect, url_for
from my_app import db, app
from my_app.catalog.models import Product, Category
from sqlalchemy.orm.util import join
catalog = Blueprint('catalog', __name__)
def template_or_json(template=None):
""""Return a dict from your view and this will either
pass it to a template or render json. Use like:
@template_or_json('template.html')
"""
def decorated(f):
@wraps(f)
def decorated_fn(*args, **kwargs):
ctx = f(*args, **kwargs)
if request.is_xhr or not template:
return jsonify(ctx)
else:
return render_template(template, **ctx)
return decorated_fn
return decorated
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@catalog.route('/')
@catalog.route('/home')
@template_or_json('home.html')
def home():
products = Product.query.all()
return {'count': len(products)}
@catalog.route('/product/<id>')
def product(id):
product = Product.query.get_or_404(id)
return render_template('product.html', product=product)
@catalog.route('/products')
@catalog.route('/products/<int:page>')
def products(page=1):
products = Product.query.paginate(page, 10)
return render_template('products.html', products=products)
@catalog.route('/product-create', methods=['GET', 'POST'])
def create_product():
if request.method == 'POST':
name = request.form.get('name')
price = request.form.get('price')
categ_name = request.form.get('category')
category = Category.query.filter_by(name=categ_name).first()
if not category:
category = Category(categ_name)
product = Product(name, price, category)
db.session.add(product)
db.session.commit()
flash('The product %s has been created' % name, 'success')
return redirect(url_for('catalog.product', id=product.id))
return render_template('product-create.html')
@catalog.route('/product-search')
@catalog.route('/product-search/<int:page>')
def product_search(page=1):
name = request.args.get('name')
price = request.args.get('price')
company = request.args.get('company')
category = request.args.get('category')
products = Product.query
if name:
products = products.filter(Product.name.like('%' + name + '%'))
if price:
products = products.filter(Product.price == price)
if company:
products = products.filter(Product.company.like('%' + company + '%'))
if category:
products = products.select_from(join(Product, Category)).filter(
Category.name.like('%' + category + '%')
)
return render_template(
'products.html', products=products.paginate(page, 10)
)
@catalog.route('/category-create', methods=['POST',])
def create_category():
name = request.form.get('name')
category = Category(name)
db.session.add(category)
db.session.commit()
return render_template('category.html', category=category)
@catalog.route('/category/<id>')
def category(id):
category = Category.query.get_or_404(id)
return render_template('category.html', category=category)
@catalog.route('/categories')
def categories():
categories = Category.query.all()
return render_template('categories.html', categories=categories)
| {
"repo_name": "nikitabrazhnik/flask2",
"path": "Module 2/Chapter04/my_app/catalog/views.py",
"copies": "1",
"size": "3469",
"license": "mit",
"hash": 2270357848639896300,
"line_mean": 29.6991150442,
"line_max": 77,
"alpha_frac": 0.6520611127,
"autogenerated": false,
"ratio": 3.791256830601093,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9942498539826823,
"avg_score": 0.00016388069485414618,
"num_lines": 113
} |
from functools import wraps
from flask import request, current_app, make_response, Response
def json_or_jsonp(func):
"""Wrap response in JSON or JSONP style"""
@wraps(func)
def _(*args, **kwargs):
mimetype = 'application/javascript'
callback = request.args.get('callback', None)
if callback is None:
content = func(*args, **kwargs)
else:
content = "%s(%s)" % (callback, func(*args, **kwargs))
return current_app.response_class(content, mimetype=mimetype)
return _
def add_response_headers(headers):
"""Add headers passed in to the response
Usage:
.. code::py
@app.route('/')
@add_response_headers({'X-Robots-Tag': 'noindex'})
def not_indexed():
# This will set ``X-Robots-Tag: noindex`` in the response headers
return "Check my headers!"
"""
def decorator(func):
@wraps(func)
def _(*args, **kwargs):
rsp = make_response(func(*args, **kwargs))
rsp_headers = rsp.headers
for header, value in headers.items():
rsp_headers[header] = value
return rsp
return _
return decorator
def gen(mimetype):
"""``gen`` is a decorator factory function, you just need to set
a mimetype before using::
@app.route('/')
@gen('')
def index():
pass
A full demo for creating a image stream is available on
`GitHub <https://github.com/kxxoling/flask-video-streaming>`__ .
"""
def streaming(func, *args, **kwargs):
@wraps(func)
def _():
return Response(func(*args, **kwargs),
mimetype=mimetype)
return _
return streaming
| {
"repo_name": "kxxoling/flask-decorators",
"path": "flask_decorators/__init__.py",
"copies": "1",
"size": "1775",
"license": "mit",
"hash": 2261038194957412000,
"line_mean": 26.734375,
"line_max": 77,
"alpha_frac": 0.5616901408,
"autogenerated": false,
"ratio": 4.186320754716981,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.524801089551698,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, current_app
import random, math
import re
import jinja2
from time import sleep
import datetime
import stripe
import emailer
from unicode_helpers import to_unicode_or_bust
import unicodedata
from sqlalchemy.exc import IntegrityError, DataError, InvalidRequestError
from sqlalchemy.orm.exc import FlushError
import logging
logger = logging.getLogger('ti.util')
# a slow decorator for tests, so can exclude them when necessary
# put @slow on its own line above a slow test method
# to exclude slow tests, run like this: nosetests -A "not slow"
def slow(f):
f.slow = True
return f
def remove_punctuation(input_string):
# from http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python
no_punc = input_string
if input_string:
no_punc = "".join(e for e in input_string if (e.isalnum() or e.isspace()))
return no_punc
# see http://www.fileformat.info/info/unicode/category/index.htm
def remove_unneeded_characters(input_string, encoding='utf-8', char_classes_to_remove=["C", "M", "P", "S", "Z"]):
input_was_unicode = True
if isinstance(input_string, basestring):
if not isinstance(input_string, unicode):
input_was_unicode = False
unicode_input = to_unicode_or_bust(input_string)
response = u''.join(c for c in unicode_input if unicodedata.category(c)[0] not in char_classes_to_remove)
if not input_was_unicode:
response = response.encode(encoding)
return response
# derived from the jsonp function in bibserver
def jsonp(f):
"""Wraps JSONified output for JSONP"""
@wraps(f)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callback:
content = str(callback) + '(' + str(f(*args,**kwargs).data) + ')'
return current_app.response_class(content, mimetype='application/javascript')
else:
return f(*args, **kwargs)
return decorated_function
def jinja_render(template_name, context):
templateLoader = jinja2.FileSystemLoader(searchpath="totalimpactwebapp/templates")
templateEnv = jinja2.Environment(loader=templateLoader)
html_template = templateEnv.get_template(template_name)
return html_template.render(context)
def pickWosItems(num_total_results, num_subset_results):
num_in_final_sample = 100
num_results_per_page = 50
num_to_sample = int(math.ceil(
float(num_subset_results * num_in_final_sample) / float(num_total_results)
))
# "id" is the index of the result in the result subset
subset_result_ids = range(1, num_subset_results)
ids_to_sample = sorted(random.sample(subset_result_ids, num_to_sample))
pages_and_ids = []
for result_id in ids_to_sample:
page = int(math.floor(result_id / num_results_per_page)) +1
pages_and_ids.append((page, result_id))
return pages_and_ids
_underscorer1 = re.compile(r'(.)([A-Z][a-z]+)')
_underscorer2 = re.compile('([a-z0-9])([A-Z])')
def camel_to_snake_case(s):
"""
from http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-camel-case
and https://gist.github.com/jaytaylor/3660565
"""
subbed = _underscorer1.sub(r'\1_\2', s)
return _underscorer2.sub(r'\1_\2', subbed).lower()
def local_sleep(interval, fuzz_proportion=.2):
"""
Add some sleep to simulate running on a server.
"""
if fuzz_proportion:
max_fuzz_distance = interval * fuzz_proportion
interval += random.uniform(-max_fuzz_distance, max_fuzz_distance)
if "localhost:5000" in request.url_root:
logger.debug(u"sleeping on local for {second} seconds".format(
second=interval))
sleep(interval)
def as_int_or_float_if_possible(input_value):
value = input_value
try:
value = int(input_value)
except (ValueError, TypeError):
try:
value = float(input_value)
except (ValueError, TypeError):
pass
return(value)
def dict_from_dir(obj, keys_to_ignore=None, keys_to_show="all"):
if keys_to_ignore is None:
keys_to_ignore = []
elif isinstance(keys_to_ignore, basestring):
keys_to_ignore = [keys_to_ignore]
ret = {}
if keys_to_show != "all":
for key in keys_to_show:
ret[key] = getattr(obj, key)
return ret
for k in dir(obj):
pass
if k.startswith("_"):
pass
elif k in keys_to_ignore:
pass
# hide sqlalchemy stuff
elif k in ["query", "query_class", "metadata"]:
pass
else:
value = getattr(obj, k)
if not callable(value):
ret[k] = value
return ret
def todict(obj, classkey=None):
# from http://stackoverflow.com/a/1118038/226013
if isinstance(obj, dict):
data = {}
for (k, v) in obj.items():
data[k] = todict(v, classkey)
return data
elif hasattr(obj, "to_dict"):
data = dict([
(key, todict(value, classkey))
for key, value in obj.to_dict().iteritems()
if key == "_tiid" or (not callable(value) and not key.startswith('_'))
])
if classkey is not None and hasattr(obj, "__class__"):
data[classkey] = obj.__class__.__name__
return data
elif hasattr(obj, "_ast"):
return todict(obj._ast())
elif type(obj) is datetime.datetime: # convert datetimes to strings; jason added this bit
return obj.isoformat()
elif hasattr(obj, "__iter__"):
return [todict(v, classkey) for v in obj]
elif hasattr(obj, "__dict__"):
data = dict([(key, todict(value, classkey))
for key, value in obj.__dict__.iteritems()
if not callable(value) and not key.startswith('_')])
if classkey is not None and hasattr(obj, "__class__"):
data[classkey] = obj.__class__.__name__
return data
else:
return obj
# getting a "decoding Unicode is not supported" error in this function?
# might need to reinstall libaries as per
# http://stackoverflow.com/questions/17092849/flask-login-typeerror-decoding-unicode-is-not-supported
class HTTPMethodOverrideMiddleware(object):
allowed_methods = frozenset([
'GET',
'HEAD',
'POST',
'DELETE',
'PUT',
'PATCH',
'OPTIONS'
])
bodyless_methods = frozenset(['GET', 'HEAD', 'OPTIONS', 'DELETE'])
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper()
if method in self.allowed_methods:
method = method.encode('ascii', 'replace')
environ['REQUEST_METHOD'] = method
if method in self.bodyless_methods:
environ['CONTENT_LENGTH'] = '0'
return self.app(environ, start_response)
class Timer(object):
def __init__(self):
self.start = datetime.datetime.now()
self.last_check = self.start
def since_last_check(self):
return self.elapsed(since_last_check=True)
def elapsed(self, since_last_check=False):
if since_last_check:
window_start = self.last_check
else:
window_start = self.start
current_datetime = datetime.datetime.now()
self.last_check = current_datetime
elapsed_seconds = (current_datetime - window_start).total_seconds()
return elapsed_seconds
def ordinal(value):
"""
Converts zero or a *postive* integer (or their string
representations) to an ordinal value.
>>> for i in range(1,13):
... ordinal(i)
...
u'1st'
u'2nd'
u'3rd'
u'4th'
u'5th'
u'6th'
u'7th'
u'8th'
u'9th'
u'10th'
u'11th'
u'12th'
>>> for i in (100, '111', '112',1011):
... ordinal(i)
...
u'100th'
u'111th'
u'112th'
u'1011th'
"""
try:
value = int(value)
except ValueError:
return value
except TypeError:
return value
if value % 100//10 != 1:
if value % 10 == 1:
ordval = u"%d%s" % (value, "st")
elif value % 10 == 2:
ordval = u"%d%s" % (value, "nd")
elif value % 10 == 3:
ordval = u"%d%s" % (value, "rd")
else:
ordval = u"%d%s" % (value, "th")
else:
ordval = u"%d%s" % (value, "th")
return ordval
# from http://code.activestate.com/recipes/576563-cached-property/
def cached_property(property_name):
"""A memoize decorator for class properties."""
@wraps(property_name)
def cached_propery_get(self):
try:
return self._cache[property_name]
except AttributeError:
self._cache = {}
except KeyError:
pass
ret = self._cache[property_name] = property_name(self)
return ret
return property(cached_propery_get)
def commit(db):
try:
db.session.commit()
except (IntegrityError, FlushError) as e:
db.session.rollback()
logger.warning(u"Error on commit, rolling back. Message: {message}".format(
message=e.message))
def random_alpha_str(length=5):
return ''.join(random.choice('ABCDEFGHJKLMNOPQRSTUVWXYZ') for i in range(length))
def mint_stripe_coupon(stripe_token, email, cost, num_subscriptions):
coupon_code = "MS_" + random_alpha_str()
print "making a stripe coupon with this code: ", coupon_code
descr = "Coupon {coupon_code}: {num_subscriptions} Impactstory subscriptions for ${cost}".format(
coupon_code=coupon_code,
num_subscriptions=num_subscriptions,
cost=cost
)
# mint a coupon from stripe
print "making a stripe coupon with this code: ", coupon_code
coupon_resp = stripe.Coupon.create(
id=coupon_code,
percent_off=100,
duration="repeating",
duration_in_months=12,
max_redemptions=num_subscriptions,
metadata={"email": email}
)
# charge the card one time
charge_resp = stripe.Charge.create(
amount=cost*100,
currency="USD",
card=stripe_token,
description=descr,
statement_description="Impactstory",
receipt_email=email,
metadata={
"coupon": coupon_code
}
)
# email them their coupon code
emailer.send(
address=email,
subject="Your code for Impactstory subscriptions",
template_name="multi-subscribe",
context={
"num_subscriptions": num_subscriptions,
"coupon_code": coupon_code
}
)
| {
"repo_name": "total-impact/total-impact-webapp",
"path": "util.py",
"copies": "2",
"size": "10827",
"license": "mit",
"hash": 3890508158740738000,
"line_mean": 26.7615384615,
"line_max": 113,
"alpha_frac": 0.6075551861,
"autogenerated": false,
"ratio": 3.6565349544072947,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5264090140507294,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, g, jsonify
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired, BadSignature
from index import app
TWO_WEEKS = 1209600
def generate_token(user, expiration=TWO_WEEKS):
s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
token = s.dumps({
'id': user.id,
'email': user.email,
}).decode('utf-8')
return token
def verify_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except (BadSignature, SignatureExpired):
return None
return data
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization', None)
if token:
string_token = token.encode('ascii', 'ignore')
user = verify_token(string_token)
if user:
g.current_user = user
return f(*args, **kwargs)
return jsonify(message="Authentication is required to access this resource"), 401
return decorated
| {
"repo_name": "pyalwin/redux",
"path": "application/utils/auth.py",
"copies": "9",
"size": "1130",
"license": "mit",
"hash": -1529423264327388000,
"line_mean": 26.5609756098,
"line_max": 89,
"alpha_frac": 0.6477876106,
"autogenerated": false,
"ratio": 4.0647482014388485,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9212535812038849,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, g, jsonify
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired, BadSignature
from .. import app
TWO_WEEKS = 1209600
FIVE_SECOND = 5
def generate_token(user, expiration=TWO_WEEKS):
s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
token = s.dumps({
'id': user.id,
'email': user.email,
}).decode('utf-8')
return token
def verify_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except (BadSignature, SignatureExpired):
return None
return data
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization', None)
if token:
string_token = token.encode('ascii', 'ignore')
user = verify_token(string_token)
if user:
g.current_user = user
return f(*args, **kwargs)
return jsonify(message="Authentication is required to access this resource"), 401
return decorated
| {
"repo_name": "mortbauer/webapp",
"path": "application/utils/auth.py",
"copies": "1",
"size": "1144",
"license": "mit",
"hash": 8752232215745918000,
"line_mean": 25.6046511628,
"line_max": 89,
"alpha_frac": 0.6451048951,
"autogenerated": false,
"ratio": 4,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.51451048951,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, g, jsonify
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, SignatureExpired, BadSignature)
from index import app
TWO_WEEKS = 1209600
def generate_token(user, expiration=TWO_WEEKS):
s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
token = s.dumps({
'id': str(user.id)
}).decode('utf-8')
return token
def verify_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except (BadSignature, SignatureExpired):
return None
return data
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization', None) if request.headers.get('Authorization', None) != None else request.args['token']
if token:
string_token = token.encode('ascii', 'ignore')
user = verify_token(string_token)
if user:
g.current_user = user
return f(*args, **kwargs)
return jsonify(message="Authentication is required to access this resource"), 401
return decorated | {
"repo_name": "groschatchauve/xCluster",
"path": "server/flask/application/utils/auth.py",
"copies": "1",
"size": "1192",
"license": "unlicense",
"hash": 3063309234137416000,
"line_mean": 28.825,
"line_max": 139,
"alpha_frac": 0.6367449664,
"autogenerated": false,
"ratio": 4.124567474048443,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5261312440448442,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, jsonify, _app_ctx_stack
import jwt
import os
from ..models import Person
from ..utils import get_one_or_create
from .. import db, graph
jwt_secret = os.environ.get('JWT_SECRET', 'superSECRETth!ng')
client_id = os.environ.get('AUTH0_ID', 'None')
# Strip start and end quotes
client_id = client_id.strip('\'')
jwt_secret = jwt_secret.strip('\'')
def handle_error(error, status_code):
resp = jsonify(error)
resp.status_code = status_code
return resp
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.headers.get('Authorization', None)
if not auth:
return handle_error({'code': 'authorization_header_missing',
'description':
'Authorization header is expected'}, 401)
parts = auth.split()
if parts[0].lower() != 'bearer':
return handle_error({'code': 'invalid_header',
'description':
'Authorization header must start with'
' Bearer'}, 401)
elif len(parts) == 1:
return handle_error({'code': 'invalid_header',
'description':
'Authorization Token not found'}, 401)
elif len(parts) > 2:
return handle_error({'code': 'invalid_header',
'description':
'Authorization header must be Bearer'
'+ \s + token'}, 401)
token = parts[1]
try:
payLoad = jwt.decode(
token,
jwt_secret,
audience=client_id
)
except jwt.ExpiredSignature:
return handle_error({'code': 'token_expired',
'description': 'token is expired'}, 401)
except jwt.DecodeError:
return handle_error({'code': 'token_invalid_signature',
'description':
'token signature is invalid'}, 401)
except jwt.InvalidAudienceError:
return handle_error({'code': 'invalid_audience',
'description': 'Incorrect audience,'
' expected: ' + client_id}, 401)
except Exception as e:
return handle_error({'code': 'invalid_header',
'description': 'Unable to parse'
' authentication token'}, 400)
user_email = payLoad['email']
print('Validating ID: {}'.format(user_email))
person, exists = get_one_or_create(
session=db.session,
model=Person,
create_method='create_from_email',
create_method_kwargs={
'confirmed': True
},
email=user_email
)
if exists:
print('User already registered')
else:
db.session.add(person)
db.session.commit()
graph.create_from_model_instance(person)
print('User registered')
_app_ctx_stack.top.current_user = payLoad
return f(*args, **kwargs)
return decorated
| {
"repo_name": "squarenomad/historia",
"path": "backend/app/api/decorators.py",
"copies": "1",
"size": "3393",
"license": "mit",
"hash": 1793465889123929900,
"line_mean": 34.34375,
"line_max": 78,
"alpha_frac": 0.4939581491,
"autogenerated": false,
"ratio": 4.805949008498583,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5799907157598584,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, jsonify, current_app
def authenticate(authorization):
from model import User
import jwt
current_app.logger.info(authorization)
try:
auth_method, token = authorization.split(':')
decoded = jwt.decode(token, '', algorithm='HS256', verify=False)
except Exception, e:
current_app.logger.warn(e)
return False
email = decoded.get('email')
current_app.logger.warn(email)
user = User.get({'email': email})
if user:
current_app.logger.warn(user.secret)
try:
if auth_method == 'KIGATA':
current_app.logger.info(user._id)
jwt.decode(token, user.secret, algorithm='HS256')
else:
return False
except jwt.DecodeError:
return False
else:
return False
return user
# require login
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
user = authenticate(request.headers.get('Authorization'))
if not user:
response = dict(status='error', data=dict(authentication='failed'))
return jsonify(response), 401
else:
kwargs['user'] = user
return f(*args, **kwargs)
return decorated_function
| {
"repo_name": "thomasbhatia/kigata",
"path": "app/contrib/mod_auth/__init__.py",
"copies": "1",
"size": "1323",
"license": "bsd-3-clause",
"hash": -8284672911269149000,
"line_mean": 26,
"line_max": 79,
"alpha_frac": 0.5993953137,
"autogenerated": false,
"ratio": 4.267741935483871,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 49
} |
from functools import wraps
from flask import request,jsonify
import hmac, hashlib
from nishu import get_application_model
def auth_decorator(func):
@wraps(func)
def decorator_func(*args,**kwargs):
user = request.headers.get('user')
api_key = request.headers.get('api_key')
# api_secret = request.headers.get('api_secret')
user_hash = request.headers.get('hash')
user_timestamp = request.headers.get('timestamp')
if not user or not api_key :
return jsonify("Error: Invalid Request"),412
if not hash or not user_timestamp or not user_hash:
return jsonify("Error: Invalid Request"), 412
server_key = get_key(api_key,user)
if not server_key:
return jsonify("key not found"),412
timestamp_hash = generate_hmac(str(server_key), str(user_timestamp))
#for get request
if request.method == 'GET':
url = request.path + '?' + request.query_string if request.query_string else request.path
server_hash = generate_hmac(str(timestamp_hash), str(url))
if hmac.compare_digest(server_hash, user_hash):
return func(*args, **kwargs)
else:
return jsonify("Error : HMAC is not matched"), 412
#change with the hmac
# server_hash = base64.base64encode(str(server_key),str(url))
# if user_hash == server_hash:
# return func(*args,**kwargs)
# else :
# return jsonify("Error: HMAC is not matched"),412
if request.method == 'POST':
#check for file upload
data = request.data.decode('utf-8')
server_hash = generate_hmac(str(timestamp_hash),data)
if hmac.compare_digest(server_hash,user_hash):
return func(*args, **kwargs)
else:
return jsonify("Error : HMAC is not matched"), 412
return decorator_func
def get_key(api_key,username):
app_model= get_application_model(api_key)
#need validation
server_key = app_model.api_key if username == app_model.username else None
return server_key
def generate_hmac(key,message):
hash = hmac.new(key,message.encode('utf-8'),hashlib.sha256).hexdigest()
return hash
| {
"repo_name": "iamrajhans/FlaskBackend",
"path": "drone/utility/auth_required.py",
"copies": "1",
"size": "2334",
"license": "mit",
"hash": -8892603922238337000,
"line_mean": 33.8358208955,
"line_max": 101,
"alpha_frac": 0.5998286204,
"autogenerated": false,
"ratio": 4.0310880829015545,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.010542267542702653,
"num_lines": 67
} |
from functools import wraps
from flask import request
from flask.ext.restful import reqparse, abort, Resource
from flask.views import http_method_funcs, View, MethodView
import six
from werkzeug.utils import cached_property
from flask.ext.presst.utils.routes import route_from
from flask_presst.parsing import PresstArgument
class NestedProxy(object):
bound_resource = None
def __init__(self, methods, collection=False, relationship_name=None):
self.methods = methods
self.collection = collection
self.relationship_name = relationship_name
def view_factory(self, name, bound_resource): # pragma: no cover
raise NotImplementedError()
class ResourceMethod(NestedProxy):
def __init__(self, fn, method, *args, **kwargs):
super(ResourceMethod, self).__init__([method], *args, **kwargs)
self.method = method
self._fn = fn
self._parser = reqparse.RequestParser(argument_class=PresstArgument)
def add_argument(self, name, location=('json', 'values'), **kwargs):
"""
Adds an argument to the :class:`reqparse.RequestParser`. When a request to a :class:`ResourceMethod` is
made, the request is first parsed. If the parsing succeeds, the results are added as keyword arguments
to the wrapped function.
:param name: name of argument
:param location: attribute of the request object to search; e.g `json` or `args`.
:param bool required: whether the argument must exist
:param default: default value
:param type: a callable, or a Flask-Presst or Flask-RESTful field
"""
self._parser.add_argument(name, location=location, **kwargs)
def view_factory(self, name, bound_resource):
def view(*args, **kwargs):
# NOTE this may be inefficient with certain collection types that do not support lazy loading:
if self.collection:
item_or_items = bound_resource.get_item_list()
else:
parent_id = kwargs.pop('parent_id')
item_or_items = bound_resource.get_item_for_id(parent_id)
# noinspection PyCallingNonCallable
kwargs.update(self._parser.parse_args())
resource_instance = bound_resource()
return self._fn.__call__(resource_instance, item_or_items, *args, **kwargs)
return view
def __get__(self, obj, *args, **kwargs):
if obj is None:
return self
return lambda *args, **kwargs: self._fn.__call__(obj, *args, **kwargs)
def resource_method(method='POST', collection=False):
"""
A decorator for attaching custom routes to a :class:`PresstResource`.
Depending on whether ``collection`` is ``True``, the route is either ``/resource/method``
or ``/resource/{id}/method`` and the decorator passes either the list of items from
:meth:`PresstResource.get_item_list` or the single item.
:param str method: one of 'POST', 'GET', 'PATCH', 'DELETE'
:param bool collection: whether this is a collection method or item method
:returns: :class:`ResourceMethod` instance
"""
def wrapper(fn):
return wraps(fn)(ResourceMethod(fn, method, collection))
return wrapper
class Relationship(NestedProxy, MethodView):
"""
:class:`Relationship` views, when attached to a :class:`PresstResource`, create a route that maps from
an item in one resource to a collection of items in another resource.
:class:`Relationship` makes use of SqlAlchemy's `relationship` attributes. To support pagination on these objects,
the relationship must return a query object. Therefore, the :func:`sqlalchemy.orm.relationship` must have the
attribute :attr:`lazy` set to ``'dynamic'``. The same goes for any :func:`backref()`.
:param resource: resource class, resource name, or SQLAlchemy model
:param str relationship_name: alternate attribute name in resource item
"""
def __init__(self, resource,
relationship_name=None, **kwargs):
super(Relationship, self).__init__(kwargs.pop('methods', ['GET', 'POST', 'DELETE']))
self.resource = resource
self.relationship_name = relationship_name
self.bound_resource = kwargs.pop('bound_resource', None)
@cached_property
def resource_class(self):
return self.bound_resource.api.get_resource_class(self.resource, self.bound_resource.__module__)
def view_factory(self, name, bound_resource):
return self.as_view(name,
bound_resource=bound_resource,
resource=self.resource,
relationship_name=self.relationship_name,
methods=self.methods)
def _resolve_item_id_from_request_data(self):
if not isinstance(request.json, six.string_types):
abort(400, message='Need resource URI in body of JSON request.')
resource_class, item_id = self.resource_class.api.parse_resource_uri(request.json)
if self.resource_class != resource_class:
abort(400, message='Wrong resource item type, expected {0}, got {1}'.format(
self.resource_class.resource_name,
self.resource_class.resource_name
))
return item_id
def get(self, parent_id):
parent_item = self.bound_resource.get_item_for_id(parent_id)
return self.resource_class.marshal_item_list(
self.resource_class.get_item_list_for_relationship(self.relationship_name, parent_item))
def post(self, parent_id, item_id=None):
parent_item = self.bound_resource.get_item_for_id(parent_id)
if not item_id: # NOTE not implemented: POST /parent/A/child/B; instead get item from request.data
item_id = self._resolve_item_id_from_request_data()
return self.resource_class.marshal_item(
self.resource_class.create_item_relationship(item_id, self.relationship_name, parent_item))
def delete(self, parent_id, item_id=None):
parent_item = self.bound_resource.get_item_for_id(parent_id)
if not item_id: # NOTE not implemented: DELETE /parent/A/child/B;, instead get item from request.data
item_id = self._resolve_item_id_from_request_data()
self.resource_class.delete_item_relationship(item_id, self.relationship_name, parent_item)
return None, 204 | {
"repo_name": "svenstaro/flask-presst",
"path": "flask_presst/nesting.py",
"copies": "2",
"size": "6441",
"license": "mit",
"hash": -3210464899304306000,
"line_mean": 41.6622516556,
"line_max": 118,
"alpha_frac": 0.6582828753,
"autogenerated": false,
"ratio": 4.105162523900574,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0015989803755294347,
"num_lines": 151
} |
from functools import wraps
from flask import request
from flask import make_response
import hashlib
TOKEN = hashlib.sha256("SAMPLE UNIQI TOKEN FOR USER").hexdigest()
TOKEN_HEADER_NAME = "MY_AUTH_TOKEN"
def validate_user(service, username, password):
return username == "john" and password == "doe123"
def authenticate(is_user_valid_func):
def auth(func):
@wraps(func)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not is_user_valid_func(auth.username, auth.password):
resp = make_response("", 401)
resp.headers["WWW-Authenticate"] = 'Basic realm="Login Required"'
return resp
kwargs[TOKEN_HEADER_NAME] = TOKEN
return func(*args, **kwargs)
return decorated
return auth
def check_token(func):
@wraps(func)
def decorated(*args, **kwargs):
if request.headers[TOKEN_HEADER_NAME] and request.headers[TOKEN_HEADER_NAME] != TOKEN:
resp = make_response("", 401)
resp.headers["X-APP-ERROR-CODE"] = 9500
resp.headers["X-APP-ERROR-MESSAGE"] = "No valid authentication token found in request"
return resp
return func(*args, **kwargs)
return decorated
| {
"repo_name": "BartGo/flask-drafts",
"path": "app/examples/lynda-webapiflask/decorators.py",
"copies": "1",
"size": "1286",
"license": "mit",
"hash": -6867504592195988000,
"line_mean": 31.15,
"line_max": 98,
"alpha_frac": 0.6283048212,
"autogenerated": false,
"ratio": 4.121794871794871,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0033167031713512247,
"num_lines": 40
} |
from functools import wraps
from flask import request
from itsdangerous import URLSafeSerializer
from config import *
import json
def response_msg(status, msg, **kwargs):
res = {}
res['status'] = status
res['msg'] = msg
for name, value in kwargs.items():
res[name] = value
return json.dumps(res), 200
def get_user_from_auth(auth_key):
s = URLSafeSerializer('secret-key', salt='be_efficient')
return s.loads(auth_key)
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
# import ipdb; ipdb.set_trace();
try:
if request.headers.get('key'):
key = request.headers.get('key')
else:
key = ""
if key:
if key != ANDROID_HEADER_KEY:
return response_msg('error', 'Authentication faiiled')
try:
user = get_user_from_auth(request.headers.get('auth_key'))
except:
user = ""
else:
user = get_user_from_auth(request.cookies['auth_key'])
if user == kwargs['name']:
return f(*args, **kwargs)
else:
return response_msg('error', 'user not authorized')
except:
return response_msg('error', 'some error occured')
return decorated_function
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
# import ipdb; ipdb.set_trace();
try:
user = get_user_from_auth(request.cookies['admin_key'])
if user == 'admin':
return f(*args, **kwargs)
else:
return response_msg('error', 'user not authorized')
except:
return response_msg('error', 'some error occured')
return decorated_function | {
"repo_name": "nirmitgoyal/longclaw",
"path": "longclaw/auth.py",
"copies": "1",
"size": "1881",
"license": "mit",
"hash": -1337179003385104100,
"line_mean": 29.3548387097,
"line_max": 78,
"alpha_frac": 0.5369484317,
"autogenerated": false,
"ratio": 4.226966292134832,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5263914723834832,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, redirect, flash
from flask.ext.login import current_user
# - Note: This code doesn't seem to work.
# from .forms import LoginForm
# def use_commmon_route_variables(f):
# @wraps(f)
# def wrap(*args, **kwargs):
# logged_in = current_user.is_authenticated()
# login_form = LoginForm(request.form)
# return wrap
def app_basic_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'administrative'
if current_user.admin_role == 'basic' or current_user.admin_role == 'super' \
or current_user.admin_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
def app_super_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'administrative'
if current_user.admin_role == 'super' or current_user.admin_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
def app_master_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'administrative'
if current_user.admin_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
def oms_basic_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'operations management'
if current_user.oms_role == 'basic' or current_user.oms_role == 'super' or current_user.oms_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
def oms_super_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'operations management'
if current_user.oms_role == 'super' or current_user.oms_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
def crm_basic_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'customer relations management'
if current_user.crm_role == 'basic' or current_user.crm_role == 'super' or current_user.crm_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
def crm_super_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'customer relations management'
if current_user.crm_role == 'super' or current_user.crm_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
def hrm_basic_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'human resources management'
if current_user.hrm_role == 'basic' or current_user.hrm_role == 'super' or current_user.hrm_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
def hrm_super_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'human resources management'
if current_user.hrm_role == 'super' or current_user.hrm_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
def ams_basic_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'accounting management'
if current_user.ams_role == 'basic' or current_user.ams_role == 'super' or current_user.ams_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
def ams_super_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'accounting management'
if current_user.ams_role == 'super' or current_user.ams_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
def mms_basic_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'marketing management'
if current_user.mms_role == 'basic' or current_user.mms_role == 'super' or current_user.mms_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
def mms_super_admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
permissions_type = 'marketing management'
if current_user.mms_role == 'super' or current_user.mms_role == 'master':
return f(*args, **kwargs)
else:
flash('You do not have sufficient {} permissions to access this area.'.format(permissions_type), 'warning')
return redirect(request.referrer)
return wrap
| {
"repo_name": "joeflack4/vanillerp",
"path": "app/route_decorators.py",
"copies": "1",
"size": "6417",
"license": "mit",
"hash": 4144072815998189000,
"line_mean": 36.9704142012,
"line_max": 119,
"alpha_frac": 0.6228767337,
"autogenerated": false,
"ratio": 3.9440688383527966,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5066945572052797,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, redirect, url_for, render_template, flash, abort, \
jsonify, session, g
from flaskr import app, db
from flaskr.models import Entry, User
def login_required(f):
@wraps(f)
def decorated_view(*args, **kwargs):
if g.user is None:
return redirect(url_for('login', next=request.path))
return f(*args, **kwargs)
return decorated_view
@app.before_request
def load_user():
user_id = session.get('user_id')
if user_id is None:
g.user = None
else:
g.user = User.query.get(session['user_id'])
@app.route('/')
def show_entries():
entries = Entry.query.order_by(Entry.id.desc()).all()
return render_template('show_entries.html', entries=entries)
@app.route('/add', methods=['POST'])
def add_entry():
entry = Entry(
title=request.form['title'],
text=request.form['text']
)
db.session.add(entry)
db.session.commit()
flash('New entry was successfully posted')
return redirect(url_for('show_entries'))
@app.route('/users/')
@login_required
def user_list():
users = User.query.all()
return render_template('user/list.html', users=users)
@app.route('/users/<int:user_id>/')
@login_required
def user_detail(user_id):
user = User.query.get(user_id)
return render_template('user/detail.html', user=user)
@app.route('/users/<int:user_id>/edit/', methods=['GET', 'POST'])
@login_required
def user_edit(user_id):
user = User.query.get(user_id)
if user is None:
abort(404)
if request.method == 'POST':
user.name=request.form['name']
user.email=request.form['email']
if request.form['password']:
user.password=request.form['password']
#db.session.add(user)
db.session.commit()
return redirect(url_for('user_detail', user_id=user_id))
return render_template('user/edit.html', user=user)
@app.route('/users/create/', methods=['GET', 'POST'])
@login_required
def user_create():
if request.method == 'POST':
user = User(name=request.form['name'],
email=request.form['email'],
password=request.form['password'])
db.session.add(user)
db.session.commit()
return redirect(url_for('user_list'))
return render_template('user/edit.html')
@app.route('/users/<int:user_id>/delete/', methods=['DELETE'])
def user_delete(user_id):
user = User.query.get(user_id)
if user is None:
response = jsonify({'status': 'Not Found'})
response.status_code = 404
return response
db.session.delete(user)
db.session.commit()
return jsonify({'status': 'OK'})
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
user, authenticated = User.authenticate(db.session.query,
request.form['email'], request.form['password'])
if authenticated:
session['user_id'] = user.id
flash('You were logged in')
return redirect(url_for('show_entries'))
else:
flash('Invalid email or password')
return render_template('login.html')
@app.route('/logout')
def logout():
session.pop('user_id', None)
flash('You were logged out')
return redirect(url_for('show_entries'))
| {
"repo_name": "nwiizo/workspace_2017",
"path": "etc/flask/app/flaskr/views.py",
"copies": "2",
"size": "3368",
"license": "mit",
"hash": -7436439972519352000,
"line_mean": 29.3423423423,
"line_max": 78,
"alpha_frac": 0.6160926366,
"autogenerated": false,
"ratio": 3.5906183368869935,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5206710973486993,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, render_template, flash, redirect, url_for, \
session, Blueprint, g, abort
from flask.ext.login import current_user, login_user, logout_user, \
login_required
from wtforms import PasswordField
from my_app import db, login_manager
from flask.ext.admin import BaseView, expose, AdminIndexView
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.admin.form import rules
from flask.ext.admin.actions import ActionsMixin
from my_app.auth.models import User, RegistrationForm, LoginForm, \
AdminUserCreateForm, AdminUserUpdateForm, generate_password_hash, \
CKTextAreaField
auth = Blueprint('auth', __name__)
def admin_login_required(func):
@wraps(func)
def decorated_view(*args, **kwargs):
if not current_user.is_admin():
return abort(403)
return func(*args, **kwargs)
return decorated_view
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
@auth.before_request
def get_current_user():
g.user = current_user
@auth.route('/')
@auth.route('/home')
def home():
return render_template('home.html')
@auth.route('/register', methods=['GET', 'POST'])
def register():
if session.get('username'):
flash('Your are already logged in.', 'info')
return redirect(url_for('auth.home'))
form = RegistrationForm(request.form)
if request.method == 'POST' and form.validate():
username = request.form.get('username')
password = request.form.get('password')
existing_username = User.query.filter_by(username=username).first()
if existing_username:
flash(
'This username has been already taken. Try another one.',
'warning'
)
return render_template('register.html', form=form)
user = User(username, password)
db.session.add(user)
db.session.commit()
flash('You are now registered. Please login.', 'success')
return redirect(url_for('auth.login'))
if form.errors:
flash(form.errors, 'danger')
return render_template('register.html', form=form)
@auth.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated():
flash('You are already logged in.')
return redirect(url_for('auth.home'))
form = LoginForm(request.form)
if request.method == 'POST' and form.validate():
username = request.form.get('username')
password = request.form.get('password')
existing_user = User.query.filter_by(username=username).first()
if not (existing_user and existing_user.check_password(password)):
flash('Invalid username or password. Please try again.', 'danger')
return render_template('login.html', form=form)
login_user(existing_user)
flash('You have successfully logged in.', 'success')
return redirect(url_for('auth.home'))
if form.errors:
flash(form.errors, 'danger')
return render_template('login.html', form=form)
@auth.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('auth.home'))
@auth.route('/admin')
@login_required
@admin_login_required
def home_admin():
return render_template('admin-home.html')
@auth.route('/admin/users-list')
@login_required
@admin_login_required
def users_list_admin():
users = User.query.all()
return render_template('users-list-admin.html', users=users)
@auth.route('/admin/create-user', methods=['GET', 'POST'])
@login_required
@admin_login_required
def user_create_admin():
form = AdminUserCreateForm(request.form)
if form.validate():
username = form.username.data
password = form.password.data
admin = form.admin.data
existing_username = User.query.filter_by(username=username).first()
if existing_username:
flash(
'This username has been already taken. Try another one.',
'warning'
)
return render_template('register.html', form=form)
user = User(username, password, admin)
db.session.add(user)
db.session.commit()
flash('New User Created.', 'info')
return redirect(url_for('auth.users_list_admin'))
if form.errors:
flash(form.errors, 'danger')
return render_template('user-create-admin.html', form=form)
@auth.route('/admin/update-user/<id>', methods=['GET', 'POST'])
@login_required
@admin_login_required
def user_update_admin(id):
user = User.query.get(id)
form = AdminUserUpdateForm(
request.form,
username=user.username,
admin=user.admin
)
if form.validate():
username = form.username.data
admin = form.admin.data
User.query.filter_by(id=id).update({
'username': username,
'admin': admin,
})
db.session.commit()
flash('User Updated.', 'info')
return redirect(url_for('auth.users_list_admin'))
if form.errors:
flash(form.errors, 'danger')
return render_template('user-update-admin.html', form=form, user=user)
@auth.route('/admin/delete-user/<id>')
@login_required
@admin_login_required
def user_delete_admin(id):
user = User.query.get(id)
user.delete()
db.session.commit()
flash('User Deleted.', 'info')
return redirect(url_for('auth.users_list_admin'))
class HelloView(BaseView):
@expose('/')
def index(self):
return self.render('some-template.html')
def is_accessible(self):
return current_user.is_authenticated() and current_user.is_admin()
class MyAdminIndexView(AdminIndexView):
def is_accessible(self):
return current_user.is_authenticated() and current_user.is_admin()
class UserAdminView(ModelView, ActionsMixin):
column_searchable_list = ('username',)
column_sortable_list = ('username', 'admin')
column_exclude_list = ('pwdhash',)
form_excluded_columns = ('pwdhash',)
form_edit_rules = (
'username', 'admin', 'roles', 'notes',
rules.Header('Reset Password'),
'new_password', 'confirm'
)
form_create_rules = (
'username', 'admin', 'roles', 'notes', 'password'
)
form_overrides = dict(notes=CKTextAreaField)
create_template = 'edit.html'
edit_template = 'edit.html'
def is_accessible(self):
return current_user.is_authenticated() and current_user.is_admin()
def scaffold_form(self):
form_class = super(UserAdminView, self).scaffold_form()
form_class.password = PasswordField('Password')
form_class.new_password = PasswordField('New Password')
form_class.confirm = PasswordField('Confirm New Password')
return form_class
def create_model(self, form):
if 'C' not in current_user.roles:
flash('You are not allowed to create users.', 'warning')
return
model = self.model(
form.username.data, form.password.data, form.admin.data,
form.notes.data
)
form.populate_obj(model)
self.session.add(model)
self._on_model_change(form, model, True)
self.session.commit()
def update_model(self, form, model):
if 'U' not in current_user.roles:
flash('You are not allowed to edit users.', 'warning')
return
form.populate_obj(model)
if form.new_password.data:
if form.new_password.data != form.confirm.data:
flash('Passwords must match')
return
model.pwdhash = generate_password_hash(form.new_password.data)
self.session.add(model)
self._on_model_change(form, model, False)
self.session.commit()
def delete_model(self, model):
if 'D' not in current_user.roles:
flash('You are not allowed to delete users.', 'warning')
return
super(UserAdminView, self).delete_model(model)
def is_action_allowed(self, name):
if name == 'delete' and 'D' not in current_user.roles:
flash('You are not allowed to delete users.', 'warning')
return False
return True
| {
"repo_name": "nikitabrazhnik/flask2",
"path": "Module 2/Chapter08/my_app/auth/views.py",
"copies": "2",
"size": "8273",
"license": "mit",
"hash": -5571358780802301000,
"line_mean": 29.304029304,
"line_max": 78,
"alpha_frac": 0.6338692131,
"autogenerated": false,
"ratio": 3.8247803975959314,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5458649610695931,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, Response,Blueprint,render_template,jsonify,current_app,abort,redirect,url_for
from bluespot.extensions import db
from bluespot.base.utils.helper import format_url
from bluespot.base.utils.forms import print_errors,get_errors
from bluespot.guest.models import Guest
bp = Blueprint('admin', __name__,template_folder='templates')
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
if username == current_app.config['LANDINGSITE']['adminusername'] and password == current_app.config['LANDINGSITE']['adminpassword'] :
return 1
else:
return None
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@bp.route('/')
@requires_auth
def client_index( ):
items = Guest.query.filter_by().all()
return render_template('admin/dashboard.html',items=items)
| {
"repo_name": "unifispot/unifispot-free",
"path": "bluespot/admin/views.py",
"copies": "1",
"size": "1406",
"license": "mit",
"hash": 8349845419367925000,
"line_mean": 30.2444444444,
"line_max": 138,
"alpha_frac": 0.6984352774,
"autogenerated": false,
"ratio": 3.9717514124293785,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5170186689829378,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, Response, current_app
from userver.object.application import Application
from binascii import unhexlify, hexlify
from binascii import Error as hex_error
from base64 import b64decode
from userver.object.device import Device
from userver.object.gateway import Gateway
from userver.object.group import Group
from userver.user.models import User
from utils.utils import validate_number
from ..oauth import oauth
from flask import abort
import time
expiration_in_seconds = 300
class ResourceName:
app = 'application'
gateway = 'gateway'
device = 'device'
group = 'group'
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
app_eui = unhexlify(username)
app = Application.query.get(app_eui)
return app.auth_token(password)
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n '
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def require_basic_or_oauth(f):
@wraps(f)
def decorated(*args, **kwargs):
# return f(User.query.get(1), *args, **kwargs)
auth = request.headers.get('Authorization')
if not auth:
return Response(response='Auth Required',
status=401,
headers={'WWW-Authenticate': 'Basic realm="Login Required"'})
auth = auth.split(' ')
if auth[0] == 'Bearer':
valid, req = oauth.verify_request([])
if valid:
return f(req.user, *args, **kwargs)
return Response(response='invalid_token', status=401)
elif auth[0] == 'Basic':
auth = b64decode(auth[1]).decode().split(':')
user = User.query.filter_by(email=auth[0]).first()
if user and user.verify_password(auth[1]):
return f(user, *args, **kwargs)
return abort(401)
return abort(401)
return decorated
def device_belong_to_user(f):
@wraps(f)
def func_wrapper(user, dev_eui):
if validate_eui(dev_eui):
bytes_eui = unhexlify(dev_eui)
device = Device.query.get(bytes_eui)
if device is None:
return resource_not_belong_to_user(ResourceName.device, dev_eui)
app = Application.query.get(device.app_eui)
if app.user_id != user.id:
return resource_not_belong_to_user(ResourceName.device, dev_eui)
return f(user, app, device)
else:
return eui_error(ResourceName.device, dev_eui)
return func_wrapper
def group_belong_to_user(f):
@wraps(f)
def func_wrapper(user, id):
if validate_eui(id):
group = Group.objects.get(unhexlify(id))
if group is None:
return resource_not_belong_to_user(ResourceName.group, id)
app = Application.query.get(group.app_eui)
if app.user_id != user.id:
return resource_not_belong_to_user(ResourceName.group, id)
return f(user, app, group)
else:
return id_error(ResourceName.group, id)
return func_wrapper
def app_belong_to_user(f):
@wraps(f)
def func_wrapper(user, app_eui, *args, **kwargs):
if validate_eui(app_eui):
app = Application.query.get(unhexlify(app_eui))
if app is None or user.id != app.user_id:
return resource_not_belong_to_user(ResourceName.app, app_eui)
elif app is None:
return resource_not_belong_to_user(ResourceName.app, app_eui)
else:
return f(user, app)
else:
return eui_error(ResourceName.app, app_eui)
return func_wrapper
# def app_has_service(f):
# @wraps(f)
# def func_wrapper(user, app, name, *arg, **kwargs):
# service = app.get_service('name')
# if service is not None:
# return f(user, app, service)
# else:
# return app_has_no_service(app.app_eui, name)
# return func_wrapper
def gateway_belong_to_user(f):
@wraps(f)
def func_wrapper(user, gateway_id, *args, **kwargs):
if validate_eui(gateway_id):
gateway = Gateway.query.get(unhexlify(gateway_id))
if gateway is not None:
if gateway.user_id == user.id:
return f(user, gateway)
else:
return resource_not_belong_to_user(ResourceName.gateway, gateway_id)
else:
return resource_not_belong_to_user(ResourceName.gateway, gateway_id)
else:
return id_error(ResourceName.gateway, gateway_id)
return func_wrapper
def device_filter_valid(f):
@wraps(f)
def func_wrapper(user, *args, **kwargs):
time0 = time.time()
group_id = request.args.get('group')
app_eui = request.args.get('app')
if group_id is not None:
if not validate_eui(group_id):
return eui_error(ResourceName.group, group_id)
group_id = unhexlify(group_id)
group = Group.objects.get(group_id)
if group is None:
return resource_not_belong_to_user(ResourceName.group, group_id)
app = Application.query.get(group.app_eui)
if app.user_id != user.id:
return resource_not_belong_to_user(ResourceName.group, group_id)
return f(user, app=app, group=group)
elif app_eui is not None:
if not validate_eui(app_eui):
return eui_error(ResourceName.app, app_eui)
bytes_app_eui = unhexlify(app_eui)
app = Application.query.get(bytes_app_eui)
if app is None or app.user_id != user.id:
return resource_not_belong_to_user(ResourceName.app, app_eui)
return f(user, app=app)
else:
time1 = time.time()
return f(user)
return func_wrapper
def group_filter_valid(f):
@wraps(f)
def func_wrapper(user, *args, **kwargs):
app_eui = request.args.get('app')
if app_eui is not None:
if not validate_eui(app_eui):
return eui_error(ResourceName.app, app_eui)
bytes_app_eui = unhexlify(app_eui)
app = Application.query.get(bytes_app_eui)
if app is None or app.user_id != user.id:
return resource_not_belong_to_user(ResourceName.app, app_eui)
return f(user, app=app)
else:
return f(user)
return func_wrapper
def msg_filter_valid(f):
@wraps(f)
def func_wrapper(user, *args, **kwargs):
group_id = request.args.get('group')
app_eui = request.args.get('app')
dev_eui = request.args.get('device')
start_ts = validate_number(request.args.get('start_ts', 0))
if start_ts is False:
return params_type_error(start_ts, request.args.get('start_ts'), 'int')
else:
start_ts = int(start_ts)
end_ts = validate_number(request.args.get('end_ts', -1))
if end_ts is False:
return params_type_error(end_ts, request.args.get('end_ts'), 'int')
else:
end_ts = int(end_ts)
max = validate_number(request.args.get('max', 0))
if max is False:
return params_type_error(max, request.args.get('max'), 'int')
max = int(max)
if dev_eui is not None:
if not validate_eui(dev_eui):
return eui_error(ResourceName.device, dev_eui)
bytes_dev_eui = unhexlify(dev_eui)
dev = Device.query.get(bytes_dev_eui)
app = Application.query.get(dev.app_eui)
if app.user_id != user.id:
return resource_not_belong_to_user(ResourceName.device, dev_eui)
else:
return f(user, app=app, device=dev, start_ts=start_ts, end_ts=end_ts, max=max)
elif group_id is not None:
if not validate_eui(group_id):
return eui_error(ResourceName.group, group_id)
group_id = unhexlify(group_id)
group = Group.objects.get(group_id)
if group is None:
return resource_not_belong_to_user(ResourceName.group, group_id)
app = Application.query.get(group.app_eui)
if app.user_id != user.id:
return resource_not_belong_to_user(ResourceName.group, group_id)
return f(user, app=app, group=group, start_ts=start_ts, end_ts=end_ts, max=max)
elif app_eui is not None:
if not validate_eui(app_eui):
return eui_error(ResourceName.app, app_eui)
bytes_app_eui = unhexlify(app_eui)
app = Application.query.get(bytes_app_eui)
if app is None or app.user_id != user.id:
return resource_not_belong_to_user('application', app_eui)
return f(user, app=app, start_ts=start_ts, end_ts=end_ts, max=max)
else:
return f(user, start_ts=start_ts, end_ts=end_ts, max=max)
return func_wrapper
def loramote_filter_valid(f):
@wraps(f)
def func_wrapper(user, *args, **kwargs):
gateway_id = request.args.get('gateway')
start_ts = validate_number(request.args.get('start_ts', 0))
if start_ts is False:
return params_type_error(start_ts, request.args.get('start_ts'), 'int')
else:
start_ts = int(start_ts)
end_ts = validate_number(request.args.get('end_ts', -1))
if end_ts is False:
return params_type_error(end_ts, request.args.get('end_ts'), 'int')
else:
end_ts = int(end_ts)
if gateway_id is not None:
if not validate_eui(gateway_id):
return eui_error(ResourceName.gateway, gateway_id)
bytes_dev_eui = unhexlify(gateway_id)
gateway = Gateway.query.get(bytes_dev_eui)
if not gateway or (gateway.user_id != user.id and (not gateway.public)):
return resource_not_belong_to_user(ResourceName.gateway, gateway_id)
else:
return f(user, gateway=gateway, start_ts=start_ts, end_ts=end_ts, *args, **kwargs)
else:
return f(user, start_ts=start_ts, end_ts=end_ts, *args, **kwargs)
return func_wrapper
def statistician_filter_valid(f):
@wraps(f)
def func_wrapper(user, *args, **kwargs):
gateway_id = request.args.get('id')
start_ts = validate_number(request.args.get('start_ts', 0))
if start_ts is False:
return params_type_error(start_ts, request.args.get('start_ts'), 'int')
else:
start_ts = int(start_ts)
end_ts = validate_number(request.args.get('end_ts', -1))
if end_ts is False:
return params_type_error(end_ts, request.args.get('end_ts'), 'int')
else:
end_ts = int(end_ts)
if gateway_id is not None:
if not validate_eui(gateway_id):
return eui_error(ResourceName.gateway, gateway_id)
bytes_dev_eui = unhexlify(gateway_id)
gateway = Gateway.query.get(bytes_dev_eui)
if gateway.user_id != user.id:
return resource_not_belong_to_user(ResourceName.gateway, gateway_id)
else:
return f(user, gateway=gateway, start_ts=start_ts, end_ts=end_ts)
else:
return f(user, start_ts=start_ts, end_ts=end_ts)
return func_wrapper
def trans_status_filter(f):
@wraps(f)
def func_wrapper(user, *args, **kwargs):
gateway_id = request.args.get('gateway')
dev_eui = request.args.get('device')
if gateway_id is not None:
if not validate_eui(gateway_id):
return eui_error(ResourceName.gateway, gateway_id)
gateway = Gateway.objects.get(unhexlify(gateway_id))
if gateway is None:
return resource_not_belong_to_user(ResourceName.gateway, gateway_id)
if gateway.user_id != user.id:
return resource_not_belong_to_user(ResourceName.gateway, gateway_id)
return f(user, gateway=gateway)
elif dev_eui is not None:
if not validate_eui(dev_eui):
return eui_error(ResourceName.device, dev_eui)
bytes_dev_eui = unhexlify(dev_eui)
dev = Device.query.get(bytes_dev_eui)
app = Application.query.get(dev.app_eui)
if app.user_id != user.id:
return resource_not_belong_to_user(ResourceName.device, dev_eui)
else:
return f(user, device=dev)
else:
return missing_params('gateway', 'device')
return func_wrapper
def validate_eui(eui):
"""
:param eui: str (16 hex)
:return:
"""
if not isinstance(eui, str):
return False
if len(eui) != 16:
return False
try:
unhexlify(eui)
return True
except hex_error:
return False
def params_type_error(name, value, type):
return Response(status=403,
response="%s should be %s, but got %s." % (name, type, value))
def resource_not_belong_to_user(name, id):
if isinstance(id, bytes):
id = hexlify(id).decode()
return Response(status=403,
response="%s:%s doesn't belong to you." % (name, id))
def missing_params(*args):
error_text = 'Missing Params '
for arg in args:
error_text = error_text + arg + ', '
error_text.rstrip(',')
error_text += ' in URL'
return Response(status=404, response=error_text)
def id_error(name, id):
if isinstance(id, bytes):
id = hexlify(id).decode()
return Response(status=404,
response="%s is not a valid %s ID. Expect 16 hex digits." % (id, name))
def eui_error(name, eui):
if isinstance(eui, bytes):
eui = hexlify(eui).decode()
return Response(status=404,
response="%s is not a valid %s EUI. Expect 16 hex digits." % (name, eui)) | {
"repo_name": "soybean217/lora-python",
"path": "UServer/http_api_oauth/api/decorators.py",
"copies": "1",
"size": "14290",
"license": "mit",
"hash": 5703446886368417000,
"line_mean": 36.4109947644,
"line_max": 98,
"alpha_frac": 0.5818754374,
"autogenerated": false,
"ratio": 3.5327564894932015,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9610501950889718,
"avg_score": 0.0008259952006966386,
"num_lines": 382
} |
from functools import wraps
from flask import request, Response, g, current_app
from ..models import *
from expiringdict import ExpiringDict
from datetime import timedelta
class APIAuthWrapper():
def __init__(self):
max_age = timedelta(minutes=10)
self.cache = ExpiringDict(max_len=100, max_age_seconds=max_age.seconds)
def auth_service(self):
return current_app.config["API_AUTH_SERVICE"]
def check_auth(self, username, password):
"""This function is called to check if a username /
password combination is valid.
"""
res = self.cache.get((username, password))
if not res:
res = self.auth_service().check_auth(username, password)
self.cache[(username, password)] = res
return res
def check_token(self, token):
"""This function is called to check if a token is valid.
"""
res = self.cache.get(token)
if not res:
res = self.auth_service().check_token(token)
self.cache[token] = res
return res
def need_authentication_response(self):
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def error_response(self, error):
"""Sends a 500 response that indicates server error"""
return Response("Error checking auth: %s" % error, 500)
def requires_auth(self, f):
@wraps(f)
def decorated(*args, **kwargs):
if request.headers.get('X-SenseiToken'):
res = self.check_token(request.headers.get('X-SenseiToken'))
else:
auth = request.authorization
if not auth:
return self.need_authentication_response()
res = self.check_auth(auth.username, auth.password)
if res.authenticated:
g.user = User(res.userinfo)
return f(*args, **kwargs)
return Response("Unauthorized", 401)
return decorated
| {
"repo_name": "WildflowerSchools/sensei",
"path": "app/api/api_auth_wrapper.py",
"copies": "1",
"size": "2201",
"license": "mit",
"hash": -6649146553288922000,
"line_mean": 33.9365079365,
"line_max": 79,
"alpha_frac": 0.597455702,
"autogenerated": false,
"ratio": 4.358415841584159,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5455871543584159,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, Response
from bson.json_util import dumps
from utils.config import get_app_configurations
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
config = get_app_configurations()
with open(config["credentials"], "r") as fh:
u, p = fh.readline().rstrip().split(",")
return username == u and password == p
def authenticate():
"""Sends a 401 response that enables basic auth"""
resp = {"status": 401, "message": "Could not verify your access level for that URL"}
return Response(dumps(resp), status=404, mimetype='application/json')
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
username = request.args.get("username", None)
password = request.args.get("password", None)
if not check_auth(username, password):
return authenticate()
return f(*args, **kwargs)
return decorated | {
"repo_name": "dgutman/ADRCPathViewer",
"path": "api/utils/auth.py",
"copies": "1",
"size": "1026",
"license": "mit",
"hash": -7708974186969005000,
"line_mean": 31.09375,
"line_max": 88,
"alpha_frac": 0.6608187135,
"autogenerated": false,
"ratio": 4.239669421487603,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5400488134987603,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, Response
from flask_philo import app
import base64
"""
http://flask.pocoo.org/snippets/8/
This module exposes a decorator that can be used in a
flask_philo app to enforce basic auth on an endpoint.
An example of usage can be found in `test/tests/test_app/views/auth_views.py`
"""
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return (
username == app.config['USERNAME'] and
password == app.config['PASSWORD']
)
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'}
)
def requires_basic_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth_string = request.headers.get('Authorization')
if auth_string:
auth_string = auth_string.replace('Basic ', '', 1)
try:
auth_string = base64.b64decode(auth_string).decode("utf-8")
username, password = auth_string.split(':')
except Exception:
return authenticate()
if not auth_string or not check_auth(username, password):
return authenticate()
return f(*args, **kwargs)
return decorated
| {
"repo_name": "maigfrga/flaskutils",
"path": "flask_philo/auth.py",
"copies": "2",
"size": "1469",
"license": "apache-2.0",
"hash": 8239104497078781000,
"line_mean": 29.6041666667,
"line_max": 77,
"alpha_frac": 0.6364874064,
"autogenerated": false,
"ratio": 4.1971428571428575,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5833630263542858,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, Response
from userver.object.application import Application
from binascii import unhexlify, hexlify
from binascii import Error as hex_error
from userver.object.device import Device
from userver.object.gateway import Gateway
from userver.object.group import Group
from userver.user.models import User
from utils.utils import validate_number
expiration_in_seconds = 300
class ResourceName:
app = 'application'
gateway = 'gateway'
device = 'device'
group = 'group'
user = 'user'
# def check_auth(username, password):
# """This function is called to check if a username /
# password combination is valid.
# """
# app_eui = unhexlify(username)
# app = Application.query.get(app_eui)
# return app.auth_token(password)
#
#
# def authenticate():
# """Sends a 401 response that enables basic auth"""
# return Response(
# 'Could not verify your access level for that URL.\n '
# 'You have to login with proper credentials', 401,
# {'WWW-Authenticate': 'Basic realm="Login Required"'})
#
#
# def requires_auth(f):
# @wraps(f)
# def decorated(*args, **kwargs):
# auth = request.headers.get('HTTP_AUTHORIZATION')
# if not auth:
# return authenticate()
# try:
# check_auth(auth.username, auth.password)
# except Exception as error:
# return Response(response='Auth Failed.\n'
# '%s.' % error,
# status=401,
# headers={'WWW-Authenticate': 'Basic realm="Login Required"'})
#
# return f(*args, **kwargs)
# return decorated
def statistician_filter_valid(f):
@wraps(f)
def func_wrapper(*args, **kwargs):
gateway_id = request.args.get('gateway')
user_id = request.args.get('user')
start_ts = validate_number(request.args.get('start_ts', 0))
if start_ts is False:
return params_type_error(start_ts, request.args.get('start_ts'), 'int')
else:
start_ts = int(start_ts)
end_ts = validate_number(request.args.get('end_ts', -1))
if end_ts is False:
return params_type_error(end_ts, request.args.get('end_ts'), 'int')
else:
end_ts = int(end_ts)
if gateway_id is not None:
if not validate_eui(gateway_id):
return eui_error(ResourceName.gateway, gateway_id)
bytes_dev_eui = unhexlify(gateway_id)
gateway = Gateway.query.get(bytes_dev_eui)
return f(gateway=gateway, start_ts=start_ts, end_ts=end_ts)
elif user_id is not None:
user = User.query.get(user_id)
if not user:
return resource_not_exist(ResourceName.user, user_id)
return f(user, start_ts=start_ts, end_ts=end_ts)
else:
return f(start_ts=start_ts, end_ts=end_ts)
return func_wrapper
def app_exists(f):
@wraps(f)
def func_wrapper(app_eui, *args, **kwargs):
app_eui = validate_eui(app_eui)
if app_eui is None:
return eui_error(ResourceName.app, app_eui)
else:
app = Application.query.get(app_eui)
if app is None:
return resource_not_exist(ResourceName.app, app_eui)
return f(app)
return func_wrapper
def device_exists(f):
@wraps(f)
def func_wrapper(dev_eui, *args, **kwargs):
dev_eui = validate_eui(dev_eui)
if dev_eui is None:
return eui_error(ResourceName.device, dev_eui)
else:
device = Device.query.get(dev_eui)
if device is None:
return resource_not_exist(ResourceName.device, dev_eui)
return f(device)
return func_wrapper
def group_exists(f):
@wraps(f)
def func_wrapper(group_id, *args, **kwargs):
group_id = validate_eui(group_id)
if group_id is None:
return eui_error(ResourceName.group, group_id)
else:
group = Group.objects.get(group_id)
if group is None:
return resource_not_exist(ResourceName.group, group)
return f(group)
return func_wrapper
def gateway_exists(f):
@wraps(f)
def func_wrapper(gateway_id, *args, **kwargs):
gateway_id = validate_eui(gateway_id)
if gateway_id is None:
return eui_error(ResourceName.gateway, gateway_id)
else:
gateway = Gateway.query.get(gateway_id)
if gateway is None:
return resource_not_exist(ResourceName.gateway, gateway_id)
return f(gateway)
return func_wrapper
def device_filter_valid(f):
@wraps(f)
def func_wrapper(*args, **kwargs):
group_id = request.args.get('group')
app_eui = request.args.get('app')
user_id = request.args.get('user')
if group_id is not None:
group_id = validate_eui(group_id)
if not group_id:
return eui_error(ResourceName.group, group_id)
group = Group.objects.get(group_id)
if group is None:
return resource_not_exist(ResourceName.group, group_id)
return f(group=group)
elif app_eui is not None:
app_eui = validate_eui(app_eui)
if not app_eui:
return eui_error(ResourceName.app, app_eui)
app = Application.query.get(app_eui)
if app is None:
return resource_not_exist(ResourceName.app, app_eui)
return f(app=app)
elif user_id is not None:
user = User.query.get(user_id)
if user is None:
return resource_not_exist(ResourceName.user, user_id)
return f(user=user)
else:
return f()
return func_wrapper
def group_filter_valid(f):
@wraps(f)
def func_wrapper(*args, **kwargs):
app_eui = request.args.get('app')
user_id = request.args.get('user')
if app_eui is not None:
app_eui = validate_eui(app_eui)
if not app_eui:
return eui_error(ResourceName.app, app_eui)
app = Application.query.get(app_eui)
if app is None:
return resource_not_exist(ResourceName.app, app_eui)
return f(app=app)
elif user_id is not None:
user = User.query.get(user_id)
if user is None:
return resource_not_exist(ResourceName.user, user_id)
return f(user=user)
else:
return f()
return func_wrapper
def msg_filter_valid(f):
@wraps(f)
def func_wrapper(*args, **kwargs):
user_id = request.args.get('user')
group_id = request.args.get('group')
app_eui = request.args.get('app')
dev_eui = request.args.get('device')
start_ts = request.args.get('start_ts', 0)
end_ts = request.args.get('end_ts', -1)
if dev_eui is not None:
dev_eui = validate_eui(dev_eui)
if not dev_eui:
return eui_error(ResourceName.device, dev_eui)
dev = Device.query.get(dev_eui)
return f(device=dev, start_ts=start_ts, end_ts=end_ts)
elif group_id is not None:
group_id = validate_eui(group_id)
if not group_id:
return eui_error(ResourceName.group, group_id)
group = Group.objects.get(group_id)
if group is None:
return resource_not_exist(ResourceName.group, group_id)
return f(group=group, start_ts=start_ts, end_ts=end_ts)
elif app_eui is not None:
app_eui = validate_eui(app_eui)
if not app_eui:
return eui_error(ResourceName.app, app_eui)
app = Application.query.get(app_eui)
return f(app=app, start_ts=start_ts, end_ts=end_ts)
elif user_id is not None:
user = User.query.get(user_id)
if not user:
return resource_not_exist(ResourceName.user, user_id)
return f(user, start_ts=start_ts, end_ts=end_ts)
return func_wrapper
def trans_status_filter(f):
@wraps(f)
def func_wrapper(*args, **kwargs):
gateway_id = request.args.get('gateway')
dev_eui = request.args.get('device')
if gateway_id is not None:
gateway_id = validate_eui(gateway_id)
if not gateway_id:
return eui_error(ResourceName.gateway, gateway_id)
gateway = Gateway.objects.get(unhexlify(gateway_id))
if gateway is None:
return resource_not_exist(ResourceName.gateway, gateway_id)
return f(gateway=gateway)
elif dev_eui is not None:
dev_eui = validate_eui(dev_eui)
if not dev_eui:
return eui_error(ResourceName.device, dev_eui)
dev = Device.query.get(dev_eui)
return f(device=dev)
else:
return missing_params('gateway', 'device')
return func_wrapper
def validate_eui(eui):
"""
:param eui: str (16 hex)
:return:
"""
if not isinstance(eui, str):
return None
if len(eui) != 16:
return None
try:
return unhexlify(eui)
except hex_error:
return None
def resource_not_exist(name, id):
if isinstance(id, bytes):
id = hexlify(id).decode()
return Response(status=404, response="%s:%s doesn't exist." % (name, id))
def app_has_no_service(app_eui, name):
if isinstance(app_eui, bytes):
app_eui = hexlify(app_eui).decode()
return Response(status=404, response='App %s has no service named %s' % (app_eui, name))
def missing_params(*args):
error_text = 'Missing Params '
for arg in args:
error_text = error_text + arg + ', '
error_text.rstrip(',')
error_text += ' in URL'
return Response(status=406, response=error_text)
def id_error(name, id):
if isinstance(id, bytes):
id = hexlify(id).decode()
return Response(status=406,
response="%s is not a valid %s ID. Expect 16 hex digits." % (name, id))
def eui_error(name, eui):
if isinstance(eui, bytes):
eui = hexlify(eui).decode()
return Response(status=406,
response="%s is not a valid %s EUI. Expect 16 hex digits." % (name, eui))
def params_type_error(name, value, type):
return Response(status=403,
response="%s should be %s, but got %s." % (name, type, value))
| {
"repo_name": "soybean217/lora-python",
"path": "UServer/admin_server/admin_http_api/api/decorators.py",
"copies": "1",
"size": "10649",
"license": "mit",
"hash": -5688880851124374000,
"line_mean": 32.8063492063,
"line_max": 93,
"alpha_frac": 0.5768616772,
"autogenerated": false,
"ratio": 3.5508502834278093,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46277119606278094,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, Response
import json
from pizza_auth.ldaptools import LDAPTools
with open('config.json', 'r') as fh:
config = json.loads(fh.read())
ldaptools = LDAPTools(config)
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
try:
user = ldaptools.getuser(username)
print user
assert(user)
print user.authGroup
assert("timerboard" in user.authGroup)
assert(ldaptools.check_credentials(username, password))
return True
except Exception as e:
print e
return False
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Services Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
| {
"repo_name": "andimiller/timerboard",
"path": "authtools.py",
"copies": "1",
"size": "1095",
"license": "mit",
"hash": -9212926809857480000,
"line_mean": 25.7073170732,
"line_max": 63,
"alpha_frac": 0.7369863014,
"autogenerated": false,
"ratio": 3.4761904761904763,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4713176777590476,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, Response
import json
from config import HR_CHATBOT_AUTHKEY
json_encode = json.JSONEncoder().encode
def check_auth(auth):
return auth == HR_CHATBOT_AUTHKEY
def authenticate():
return Response(json_encode({'ret': 401, 'response': {'text': 'Could not verify your access'}}),
mimetype="application/json")
def get_token_auth_header():
"""Obtains the access token from the Authorization Header
"""
auth = request.headers.get("Authorization", None)
if not auth:
raise AuthError({"code": "authorization_header_missing",
"description":
"Authorization header is expected"}, 401)
parts = auth.split()
if parts[0].lower() != "bearer":
raise AuthError({"code": "invalid_header",
"description":
"Authorization header must start with"
" Bearer"}, 401)
elif len(parts) == 1:
raise AuthError({"code": "invalid_header",
"description": "Token not found"}, 401)
elif len(parts) > 2:
raise AuthError({"code": "invalid_header",
"description":
"Authorization header must be"
" Bearer token"}, 401)
token = parts[1]
return token
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.args.get('Auth')
if not auth or not check_auth(auth):
return authenticate()
return f(*args, **kwargs)
return decorated
| {
"repo_name": "hansonrobotics/chatbot",
"path": "src/chatbot/server/auth.py",
"copies": "1",
"size": "1655",
"license": "mit",
"hash": -8029137637932749000,
"line_mean": 29.0909090909,
"line_max": 100,
"alpha_frac": 0.5564954683,
"autogenerated": false,
"ratio": 4.534246575342466,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5590742043642466,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request, Response
import log
log = logging.getLogger('simple_example')
password = None
gm_password = None
def check_auth(try_password):
"""This function is called to check if a password is valid.
"""
return try_password == password or try_password == gm_password
def check_gm_auth(try_password):
"""This function is called to check if a password is valid.
"""
return try_password == gm_password
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
def requires_gm_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_gm_auth(auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
| {
"repo_name": "jghibiki/Cursed",
"path": "terminal/authentication.py",
"copies": "1",
"size": "1247",
"license": "mit",
"hash": -5726900198293240000,
"line_mean": 28,
"line_max": 66,
"alpha_frac": 0.6623897354,
"autogenerated": false,
"ratio": 4.129139072847682,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5291528808247682,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import request,url_for,session,Response,g
import api
import urllib.parse
import flask
import os
SRC_DIR=os.path.dirname(os.path.realpath(__file__))
def redirect(path,next_path=None):
print(next_path)
if(next_path):
if(next_path[-1]=="?"):
next_path = next_path[:-1]
next_path = urllib.parse.quote(next_path)
path += "?next=" + next_path
res = Response("Redirect...")
res.headers["Content-Type"] = "text/plain"
res.headers["Location"] = path
res.autocorrect_location_header = False
return res,302
def login_required(f=None,rulesAgree=True):
def wrap_(f):
@wraps(f)
def df(*args,**kwargs):
if g.get("my"):
my = g.my
if(my["isSuspended"]):
return redirect("/suspend")
if(rulesAgree and not my.get("rulesAgree",False)):
if(api.get("web/rules_agree_period")["result"]):
return redirect("/rules_agree")
return f(*args,**kwargs)
else:
return redirect('/login',request.full_path)
return df
if(f):
wrap_ = wrap_(f)
return wrap_
def render_template(*wargs,**kwargs):
if g.get("my"):
kwargs["my"]=g.my
else:
kwargs["my"]=None
git_head=open(SRC_DIR+"/../.git/HEAD","r").read()
if 'ref:' in git_head:
git_ref=git_head.split()[1]
git_commit=open(SRC_DIR+"/../.git/"+git_ref).read()
else:
git_commit=git_head
kwargs["git_commit"]=git_commit[:7]
return flask.render_template(*wargs,**kwargs)
| {
"repo_name": "kyoppie/kyoppie-web",
"path": "src/utils.py",
"copies": "1",
"size": "1659",
"license": "mit",
"hash": -1634354299510523600,
"line_mean": 32.18,
"line_max": 68,
"alpha_frac": 0.5563592526,
"autogenerated": false,
"ratio": 3.5524625267665955,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46088217793665953,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import session, Blueprint, url_for, request, redirect, flash
from flask.ext.login import login_required
from .angular_view import register_or_login_user
from ..extensions import oauth
users = Blueprint("users", __name__)
facebook = oauth.remote_app(
'facebook',
base_url='https://graph.facebook.com/',
request_token_url=None,
access_token_url='/oauth/access_token',
authorize_url='https://www.facebook.com/dialog/oauth',
app_key="FACEBOOK",
request_token_params={'scope': 'email, public_profile'})
@facebook.tokengetter
def get_facebook_token(token=None):
"""get facebook oauth token"""
return session.get('facebook_token')
def require_login(view):
"""direct user based on logged in status"""
@wraps(view)
def decorated_view(*args, **kwargs):
if 'facebook_token' in session:
return view(*args, **kwargs)
else:
return redirect(url_for("users.login"))
return decorated_view
@users.route("/facebook/login")
def facebook_login():
"""log in user via facebook"""
session.pop('facebook_token', None)
return facebook.authorize(callback=url_for('.facebook_authorized',
_external=True,
next=request.args.get('next')))
@users.route('/login/facebook/authorized', methods=["GET", "POST"])
def facebook_authorized():
"""verify that user completed facebook authorization"""
resp = facebook.authorized_response()
if resp is None:
flash('You denied the request to sign in.')
return redirect("#/")
session['facebook_token'] = (resp['access_token'],)
me = facebook.get('/me')
session['facebook_name'] = me.data['first_name']
print("\n\nYour name is", me.data['first_name'])
for key in me.data.keys():
print("{} = {}".format(key, me.data[key]))
user = {"name": me.data['name'],
"gender": me.data['gender'],
"email": me.data['email'],
"facebook_id": me.data['id']}
flash('You were signed in as {}'.format(me.data['email']))
return register_or_login_user(user)
@users.route('/facebook/photo')
@users.route('/facebook/photo/<facebook_id>')
@login_required
def facebook_photo(facebook_id=None):
"""return user's facebook profile picture"""
if facebook_id:
photo = facebook.get(
'/{}/picture?redirect=false&height=250&width=250'.format(
facebook_id))
else:
photo = facebook.get('/me/picture?redirect=false&height=250&width=250')
return photo.data['data']['url']
| {
"repo_name": "Bayesian-Skulls/carpool_app",
"path": "carpool_app/views/users.py",
"copies": "1",
"size": "2653",
"license": "mit",
"hash": -6927446006144994000,
"line_mean": 32.1625,
"line_max": 79,
"alpha_frac": 0.6226912929,
"autogenerated": false,
"ratio": 3.8008595988538683,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9923550891753868,
"avg_score": 0,
"num_lines": 80
} |
from functools import wraps
from flask import session, flash, redirect, url_for, abort
from apps.models import User
def current_user():
user = None
if 'user_id' in session:
user_id = session['user_id']
user = User.get(User.id == user_id)
return user
def admin_required(func):
@wraps(func)
def decorator(*args, **kwargs):
if not current_user():
flash('Anda harus masuk dahulu untuk melihat halaman ini', 'error')
return redirect(url_for('login'))
elif current_user():
user = current_user()
if user.level.name != 'admin':
return abort(401)
return func(*args, **kwargs)
return decorator
def dosen_required(func):
@wraps(func)
def decorator(*args, **kwargs):
if not current_user():
flash('Anda harus masuk dahulu untuk melihat halaman ini', 'error')
return redirect(url_for('login'))
elif current_user():
user = current_user()
if user.level.name != 'dosen':
return abort(401)
return func(*args, **kwargs)
return decorator
def mhs_required(func):
@wraps(func)
def decorator(*args, **kwargs):
if not current_user():
flash('Anda harus masuk dahulu untuk melihat halaman ini', 'error')
return redirect(url_for('login'))
elif current_user():
user = current_user()
if user.level.name != 'mahasiswa':
return abort(401)
return func(*args, **kwargs)
return decorator
| {
"repo_name": "ap13p/elearn",
"path": "apps/decorators.py",
"copies": "1",
"size": "1601",
"license": "bsd-3-clause",
"hash": -4234044272179362300,
"line_mean": 29.7884615385,
"line_max": 79,
"alpha_frac": 0.572142411,
"autogenerated": false,
"ratio": 3.876513317191283,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9940951093082802,
"avg_score": 0.0015409270216962523,
"num_lines": 52
} |
from functools import wraps
from flask import session, redirect, url_for, request, abort
from alexandria import mongo
def not_even_one(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if mongo.Books.find_one() is None:
return redirect(url_for('upload'))
return f(*args, **kwargs)
return decorated_function
def authenticated(f):
@wraps(f)
def decorated_function(*args, **kwargs):
print request.method
if request.method == 'GET':
token = request.args.get('token')
user = mongo.Users.find_one({'tokens.token': token})
if not (token and user):
abort(403)
elif request.method == 'POST':
token = request.form.get('token')
user = mongo.Users.find_one({'tokens.token': token})
if not (token and user):
abort(403)
else:
abort(405)
return f(*args, **kwargs)
return decorated_function
def administrator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
user = mongo.Users.find_one({'username': session.get('username')})
if user['role'] != 0:
return redirect(url_for('index'))
return f(*args, **kwargs)
return decorated_function
| {
"repo_name": "citruspi/Alexandria",
"path": "alexandria/decorators.py",
"copies": "1",
"size": "1306",
"license": "mit",
"hash": -4601929875483794000,
"line_mean": 22.3214285714,
"line_max": 74,
"alpha_frac": 0.5727411945,
"autogenerated": false,
"ratio": 4.043343653250774,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0030148423005565863,
"num_lines": 56
} |
from functools import wraps
from flask import session, request, redirect, url_for
from flask_oauthlib.client import OAuth, OAuthException
from . import app
auth = OAuth().remote_app(
'recurse',
base_url = 'https://www.recurse.com/api/v1/',
access_token_url = 'https://www.recurse.com/oauth/token',
authorize_url = 'https://www.recurse.com/oauth/authorize',
consumer_key = app.config["CONSUMER_KEY"],
consumer_secret = app.config["CONSUMER_SECRET"],
access_token_method = 'POST'
)
@auth.tokengetter
def get_token(token=None):
# a decorated tokengetter function is required by the oauth module
return session.get('oauth_token')
def get_login():
# knowledge of session['login'] is only in here, oauth_authorized, and logout
return session.get('login')
def login_required(route):
# in large apps it is probably better to use the Flask-Login extension than
# this route decorator because this decorator doesn't provide you with
# 1. user access levels or
# 2. the helpful abstraction of an "anonymous" user (not yet logged in)
@wraps(route)
def wrapper(*args, **kwargs):
kwargs.update(login=get_login())
if kwargs['login']:
return route(*args, **kwargs)
else:
return redirect(url_for('login', return_url=request.url))
# redirect includes "next=request.url" so that after logging in the
# user will be sent to the page they were trying to access
return wrapper | {
"repo_name": "mikkqu/rc-chrysalis",
"path": "scapp/oauth.py",
"copies": "1",
"size": "1530",
"license": "bsd-2-clause",
"hash": 8932920542284013000,
"line_mean": 33.7954545455,
"line_max": 81,
"alpha_frac": 0.6692810458,
"autogenerated": false,
"ratio": 3.9130434782608696,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5082324524060869,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask import url_for as flask_url_for, redirect, render_template, request, g, abort
from flask_login import login_required
from piipod import config
import flask_login
def current_user():
"""Returns currently-logged-in user"""
return flask_login.current_user
def render(f, *args, **kwargs):
"""Render templates with defaults"""
for k, v in config.items():
kwargs.setdefault('cfg_%s' % k, v)
return render_template(f, *args,
domain=config['domain'],
request=request,
g=g,
logout=request.args.get('logout', False),
the_url=url_for,
current_url=current_url,
**kwargs)
def anonymous_required(f):
"""Decorator for views that require anonymous users (e.g., sign in)"""
@wraps(f)
def decorator(*args, **kwargs):
if flask_login.current_user.is_authenticated:
return redirect(url_for('dashboard.home'))
return f(*args, **kwargs)
return decorator
def requires(*permissions):
"""Decorator for views, restricting access to the roles listed"""
def wrap(f):
@wraps(f)
def decorator(*args, **kwargs):
if not all(flask_login.current_user.can(p) for p in permissions):
if getattr(g, 'group', None):
return redirect(url_for('group.home'))
return redirect(url_for('dashboard.home'))
return f(*args, **kwargs)
return decorator
return wrap
def strip_subdomain(string):
"""Strip subdomain prefix if applicable"""
if '/subdomain' not in request.path or not getattr(g, 'group', None):
return string
string = string.replace('/subdomain', '')
if '/%s' % g.group.url in string:
string = string.replace('/%s' % g.group.url, '', 1)
return string
def current_url():
"""Return current URL"""
return strip_subdomain(request.path)
def url_for(*args, **kwargs):
"""Special url function for subdomain websites"""
return strip_subdomain(flask_url_for(*args, **kwargs))
| {
"repo_name": "alvinwan/piipod",
"path": "piipod/views.py",
"copies": "2",
"size": "2072",
"license": "apache-2.0",
"hash": -7066383654344809000,
"line_mean": 29.4705882353,
"line_max": 88,
"alpha_frac": 0.625,
"autogenerated": false,
"ratio": 3.9242424242424243,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5549242424242424,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from flask_login import current_user
from flask import flash, redirect, request, abort
from comport.department.models import Extractor, Department
def authorized_access_only(dataset=None):
''' Decorates views that require authentication if the department is not public
'''
def check_authorized(view_function):
@wraps(view_function)
def decorated_function(*args, **kwargs):
try:
department = Department.query.filter_by(short_name=kwargs["short_name"].upper()).first()
except KeyError:
department = Department.query.filter_by(id=kwargs["department_id"]).first()
# check whether the current dataset is public
dataset_is_public = True
if dataset:
try:
dataset_is_public = getattr(department, "is_public_{}".format(dataset))
except ValueError:
dataset_is_public = True
# check whether the user has access to this department
if current_user.is_authenticated():
user_has_dept_access = current_user.has_department(department.id) or current_user.is_admin()
else:
user_has_dept_access = False
# abort with a 403 Forbidden if the department or dataset's not public and the user's not authorized to access it
if (not department.is_public or not dataset_is_public) and (not current_user.is_authenticated() or not user_has_dept_access):
abort(403)
return view_function(*args, **kwargs)
return decorated_function
return check_authorized
def requires_roles(required_roles):
'''
Takes in a list of roles and checks whether the user
has access to those role
'''
def check_roles(view_function):
@wraps(view_function)
def decorated_function(*args, **kwargs):
def names(role):
return role.name
if not all(r in map(names, current_user.roles) for r in required_roles):
flash('You do not have sufficient permissions to do that', 'alert alert-danger')
return redirect(request.args.get('next') or '/')
return view_function(*args, **kwargs)
return decorated_function
return check_roles
def admin_or_department_required():
'''
Reads department from current_user and checks whether the user
has access to that department or is an admin
'''
def check_department(view_function):
@wraps(view_function)
def decorated_function(*args, **kwargs):
if current_user.has_department(kwargs["department_id"]) or current_user.is_admin():
return view_function(*args, **kwargs)
flash('You do not have sufficient permissions to do that', 'alert alert-danger')
return redirect(request.args.get('next') or '/')
return decorated_function
return check_department
def extractor_auth_required():
'''
Ensures that current_user is an extractor with access to the correct department
'''
def check_extractor(view_function):
@wraps(view_function)
def decorated_function(*args, **kwargs):
username = request.authorization.username
password = request.authorization.password
found_extractor = Extractor.query.filter_by(username=username).first()
if not found_extractor:
return ("No extractor with that username!", 401)
if not found_extractor.check_password(password):
return ("Extractor authorization failed!", 401)
return view_function(*args, **kwargs)
return decorated_function
return check_extractor
| {
"repo_name": "codeforamerica/comport",
"path": "comport/decorators.py",
"copies": "1",
"size": "3787",
"license": "bsd-3-clause",
"hash": -3619953759276854000,
"line_mean": 40.6153846154,
"line_max": 137,
"alpha_frac": 0.6311064167,
"autogenerated": false,
"ratio": 4.640931372549019,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5772037789249019,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from google.appengine.api import users
from app.user.forms import SettingsForm
from app.user.models import UserModel, create_user, update_user
from flask import Blueprint, redirect, request, g, url_for, render_template
USER_MODULE = Blueprint('user', __name__, url_prefix='/user')
def login_required(func):
"""Requires standard login credentials"""
@wraps(func)
def decorated_view(*args, **kwargs):
if not users.get_current_user():
return redirect(g.auth_url)
return func(*args, **kwargs)
return decorated_view
def get_authed_user():
session_user = users.get_current_user()
if session_user:
user_id = session_user.user_id()
existing_user = UserModel.build_key(user_id=user_id).get()
if not existing_user:
existing_user = create_user(user_id)
return existing_user
return None
@USER_MODULE.route('/settings/', methods=['GET', 'POST'])
@login_required
def settings():
form = SettingsForm(request.form, obj=g.user)
if request.method == 'POST' and form.validate():
update_user(g.user.user_id, form.name.data, form.company_name.data)
return redirect(url_for('user.settings'))
g.context['api_key'] = g.user.api_key
return render_template('user/settings.html', form=form, **g.context)
@USER_MODULE.route('/dashboard/')
@login_required
def user_dashboard():
if not g.is_logged_in:
return redirect(g.auth_url)
return render_template("user/dashboard.html", **g.context)
| {
"repo_name": "sourlows/rating-cruncher",
"path": "src/app/user/views.py",
"copies": "1",
"size": "1547",
"license": "apache-2.0",
"hash": 3427060543305969000,
"line_mean": 29.94,
"line_max": 75,
"alpha_frac": 0.67291532,
"autogenerated": false,
"ratio": 3.5481651376146788,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9721080457614679,
"avg_score": 0,
"num_lines": 50
} |
from functools import wraps
from google.appengine.ext import db
def user_logged_in(function):
"""checks whether user is logged in"""
@wraps(function)
def wrapper(self, *args, **kwargs):
if not self.user:
self.error(403)
return self.redirect("/")
else:
kwargs["user"] = self.user
return function(self, *args, **kwargs)
return wrapper
def user_owns_comment(function):
"""Check that user owns comment"""
@wraps(function)
def wrapper(self, *args, **kwargs):
comment = kwargs["comment"]
user = kwargs["user"]
if not comment:
self.error(404)
if self.request.referer:
self.redirect(self.request.referer)
else:
self.redirect("/")
return
else:
if user.key() == comment.author.key():
return function(self, *args, **kwargs)
else:
self.error(403)
return self.redirect("/%s" % comment.post.key().id())
return wrapper
def user_owns_post(function):
"""Check that post exists and return error 403 if user owns post"""
@wraps(function)
def wrapper(self, *args, **kwargs):
post = kwargs['post']
post_id = post.key().id()
if not post:
self.error(404)
if self.request.referer:
self.redirect(self.request.referer)
else:
self.redirect("/")
return
else:
if self.user.key() == post.author.key():
kwargs["user"] = self.user
return function(self, *args, **kwargs)
else:
self.error(403)
return self.redirect("/%s" % post_id)
return wrapper
def comment_exists(function):
@wraps(function)
def wrapper(self, *args, **kwargs):
comment_id = args[0]
key = db.Key.from_path("Comment", int(comment_id))
comment = db.get(key)
if comment:
kwargs['comment'] = comment
return function(self, *args, **kwargs)
else:
self.error(404)
return
return wrapper
def post_exists(function):
@wraps(function)
def wrapper(self, *args, **kwargs):
post_id = args[0]
key = db.Key.from_path("Post", int(post_id))
post = db.get(key)
if post:
kwargs['post'] = post
return function(self, *args, **kwargs)
else:
self.error(404)
return
return wrapper
| {
"repo_name": "brusznicki/multi-user-blog",
"path": "helpers/decorators.py",
"copies": "1",
"size": "2597",
"license": "mit",
"hash": 5481319014965212000,
"line_mean": 27.2282608696,
"line_max": 71,
"alpha_frac": 0.5225259915,
"autogenerated": false,
"ratio": 4.1552,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.51777259915,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from hashlib import sha1
import hmac
import json
from django.db import models
from django.db.models.query import QuerySet
from django.conf import settings
from django.core.cache import cache
import logging
logger = logging.getLogger(__name__)
DEFAULT = 60 * 60 * 6 # 6 hours
EXTENDED = 60 * 60 * 24 * 3 # 3 days
FOUND_KEY = 'found_in_cache'
NOT_FOUND_KEY = 'not_found_in_cache'
#######################
### General Methods ###
#######################
def set(key, value, timeout=DEFAULT):
if not settings.ENABLE_DB_CACHE:
return
if isinstance(value, QuerySet): # Can't JSON serialize a QuerySet
value = list(value)
try:
value = json.dumps(value)
except TypeError as ex:
logger.warning(
'json.dumps() for {} failed for reason: {}'.format(key, ex))
else:
logger.info("Cache is set for key: %s" % key)
return cache.set(key, value, timeout=timeout)
def get(key):
if not settings.ENABLE_DB_CACHE:
return
value = cache.get(key)
track_cache(value)
if value:
logger.info("Cache retrieved for key: %s" % key)
else:
logger.info("Cache retrieval failed for key: %s" % key)
return json.loads(value) if value else value
def delete(key):
if not settings.ENABLE_DB_CACHE:
return
logger.info("Cache is deleted for key: %s" % key)
return cache.delete(key)
def clear():
logger.info("Cache cleared")
return cache.clear()
### Internal Monitoring ###
def track_cache(value):
key = NOT_FOUND_KEY if value is None else FOUND_KEY
try:
cache.incr(key)
except ValueError:
cache.set(key, 1, timeout=None)
def found():
return cache.get(FOUND_KEY)
def not_found():
return cache.get(NOT_FOUND_KEY)
##########################
### Function Decorator ###
##########################
def auto_set(key_template=None, key_params=None, timeout=DEFAULT, is_update=False, set_false=True):
'''Will cache a function using a key defined in the arguments.
Example: (key_template='info_{}', key_params=(0, 'id'))
This will result in a cache key like 'info_394', with member.id = 394
Arguments:
key_template -- str, with {} to represent dynamic portions of key.
key_params -- list of tuples. The first element in the tuple can be either
an integer or a string. If an integer, it refers to the position of
a positional argument being passed to the function being
wrapped. If a string, it refers to the name of a keyword argument.
Additional elements of the tuple are attributes to be called on that
argument.
For instance: [(0, 'id'), ('work','company','id')]
Keyword Arguments:
is_update -- bool, will update value in cache for the key (default False)
set_false -- bool, will not cache if return value is False (default True)
'''
def function_wrapper(f):
@wraps(f)
def wrapped_function(*args, **kwargs):
cache_key = create_key(key_template or f.__name__, key_params, locals())
if is_update:
delete(cache_key)
data = None if is_update else get(cache_key)
if data is None:
data = f(*args, **kwargs)
if data or set_false:
set(cache_key, data, timeout)
return data
return wrapped_function
return function_wrapper
def create_key(key_template, key_params, local_vars):
'''Create the cache key by combining the key template with local variables.
Ex: key_template = 'info_{}_{}'
key_params = [(0, 'id'), ('do_reduc',)]
local_vars = {'args':[member], 'kwargs': {'do_reduc': True}}
'''
args = local_vars['args']
kwargs = local_vars['kwargs']
key_params = key_params or []
if not isinstance(key_params, list):
key_params = [key_params]
key_args = []
if key_params:
for p in key_params:
key_arg = args[p[0]] if isinstance(p[0], int) else kwargs[p[0]]
for attr in p[1:]: # Additional elements are attributes of arg
if hasattr(key_arg, attr):
key_arg = getattr(key_arg, attr)
else:
# it's possible that key_arg is None
key_arg = "default"
key_args.append(key_arg)
try:
cache_key = key_template.format(*key_args)
return cache_key
except IndexError as ex:
logger.info("Cache key creation failed for {}".format(key_template))
raise ex
else:
cache_key = key_template
for a in args:
a = a.__class__ if isinstance(a, models.Manager) else a
cache_key = cache_key + str(a)
for k in kwargs:
cache_key = cache_key + str(kwargs[k])
cache_key = generate_hash(cache_key)
return cache_key
def generate_hash(base=None):
base = base or uuid.uuid4().bytes
return hmac.new(base, digestmod=sha1).hexdigest()
| {
"repo_name": "kronosapiens/precisicache",
"path": "precisicache.py",
"copies": "1",
"size": "5063",
"license": "mit",
"hash": -3296140219135629000,
"line_mean": 32.3092105263,
"line_max": 99,
"alpha_frac": 0.5956942524,
"autogenerated": false,
"ratio": 3.864885496183206,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9937926392578906,
"avg_score": 0.004530671200859879,
"num_lines": 152
} |
from functools import wraps
from htmlmin import Minifier
from flask import request, current_app
import warnings
class HTMLMIN(object):
def __init__(self, app=None, **kwargs):
self.app = app
if app is not None:
self.init_app(app)
default_options = {
'remove_comments': True,
'reduce_empty_attributes': True,
'remove_optional_attribute_quotes': False
}
default_options.update(kwargs)
self._exempt_routes = set()
self._html_minify = Minifier(
**default_options)
def init_app(self, app):
app.config.setdefault('MINIFY_HTML', False)
if 'MINIFY_PAGE' in app.config:
app.config['MINIFY_HTML'] = app.config['MINIFY_PAGE']
warnings.warn(
'MINIFY_PAGE is deprecated, use MINIFY_HTML instead',
DeprecationWarning,
stacklevel=2
)
if app.config['MINIFY_HTML']:
app.after_request(self.response_minify)
def response_minify(self, response):
"""
minify response html to decrease traffic
"""
if response.content_type == u'text/html; charset=utf-8':
endpoint = request.endpoint or ''
view_func = current_app.view_functions.get(endpoint, None)
name = (
'%s.%s' % (view_func.__module__, view_func.__name__)
if view_func else ''
)
if name in self._exempt_routes:
return response
response.direct_passthrough = False
response.set_data(
self._html_minify.minify(response.get_data(as_text=True))
)
return response
return response
def exempt(self, obj):
"""
decorator to mark a view as exempt from htmlmin.
"""
name = '%s.%s' % (obj.__module__, obj.__name__)
@wraps(obj)
def __inner(*a, **k):
return obj(*a, **k)
self._exempt_routes.add(name)
return __inner
| {
"repo_name": "hamidfzm/Flask-HTMLmin",
"path": "flask_htmlmin/__init__.py",
"copies": "1",
"size": "2085",
"license": "bsd-3-clause",
"hash": -8687123101209118000,
"line_mean": 27.9583333333,
"line_max": 73,
"alpha_frac": 0.5342925659,
"autogenerated": false,
"ratio": 4.1783567134268536,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 72
} |
from functools import wraps
from http import HTTPStatus
from flask import abort, request
from flask_login import current_user
from flask_principal import Permission, RoleNeed, UserNeed
from flask_security.decorators import auth_required as flask_security_auth_required
from backend.utils import was_decorated_without_parenthesis
def anonymous_user_required(*args, **kwargs):
"""Decorator requiring no user be logged in
Aborts with HTTP 403: Forbidden if there is an authenticated user
"""
def wrapper(fn):
@wraps(fn)
def decorated(*args, **kwargs):
if current_user.is_authenticated:
abort(HTTPStatus.FORBIDDEN)
return fn(*args, **kwargs)
return decorated
if was_decorated_without_parenthesis(args):
return wrapper(args[0])
return wrapper
def auth_required(*args, **kwargs):
"""Decorator for requiring an authenticated user, optionally with roles
Roles are passed as keyword arguments, like so:
@auth_required(role='REQUIRE_THIS_ONE_ROLE')
@auth_required(roles=['REQUIRE', 'ALL', 'OF', 'THESE', 'ROLES'])
@auth_required(one_of=['EITHER_THIS_ROLE', 'OR_THIS_ONE'])
One of role or roles kwargs can also be combined with one_of:
@auth_required(role='REQUIRED', one_of=['THIS', 'OR_THIS'])
# equivalent, but more clearly describing the resultant behavior:
@auth_required(role='REQUIRED', and_one_of=['THIS', 'OR_THIS'])
Aborts with HTTP 401: Unauthorized if no user is logged in, or
HTTP 403: Forbidden if any of the specified role checks fail
"""
required_roles = []
one_of_roles = []
if not was_decorated_without_parenthesis(args):
if 'role' in kwargs and 'roles' in kwargs:
raise RuntimeError('can only pass one of `role` or `roles` kwargs to auth_required')
elif 'role' in kwargs:
required_roles = [kwargs['role']]
elif 'roles' in kwargs:
required_roles = kwargs['roles']
if 'one_of' in kwargs and 'and_one_of' in kwargs:
raise RuntimeError('can only pass one of `one_of` or `and_one_of` kwargs to auth_required')
elif 'one_of' in kwargs:
one_of_roles = kwargs['one_of']
elif 'and_one_of' in kwargs:
one_of_roles = kwargs['and_one_of']
def wrapper(fn):
@wraps(fn)
@flask_security_auth_required('session', 'token')
@roles_required(*required_roles)
@roles_accepted(*one_of_roles)
def decorated(*args, **kwargs):
return fn(*args, **kwargs)
return decorated
if was_decorated_without_parenthesis(args):
return wrapper(args[0])
return wrapper
def auth_required_same_user(*args, **kwargs):
"""Decorator for requiring an authenticated user to be the same as the
user in the URL parameters. By default the user url parameter name to
lookup is 'id', but this can be customized by passing an argument:
@auth_require_same_user('user_id')
@bp.route('/users/<int:user_id>/foo/<int:id>')
def get(user_id, id):
# do stuff
Any keyword arguments are passed along to the @auth_required decorator,
so roles can also be specified in the same was as it, eg:
@auth_required_same_user('user_id', role='ROLE_ADMIN')
Aborts with HTTP 403: Forbidden if the user-check fails
"""
auth_kwargs = {}
user_id_parameter_name = 'id'
if not was_decorated_without_parenthesis(args):
auth_kwargs = kwargs
if args and isinstance(args[0], str):
user_id_parameter_name = args[0]
def wrapper(fn):
@wraps(fn)
@auth_required(**auth_kwargs)
def decorated(*args, **kwargs):
try:
user_id = request.view_args[user_id_parameter_name]
except KeyError:
raise KeyError('Unable to find the user lookup parameter '
f'{user_id_parameter_name} in the url args')
if not Permission(UserNeed(user_id)).can():
abort(HTTPStatus.FORBIDDEN)
return fn(*args, **kwargs)
return decorated
if was_decorated_without_parenthesis(args):
return wrapper(args[0])
return wrapper
def roles_required(*roles):
"""Decorator which specifies that a user must have all the specified roles.
Aborts with HTTP 403: Forbidden if the user doesn't have the required roles
Example::
@app.route('/dashboard')
@roles_required('ROLE_ADMIN', 'ROLE_EDITOR')
def dashboard():
return 'Dashboard'
The current user must have both the `ROLE_ADMIN` and `ROLE_EDITOR` roles
in order to view the page.
:param args: The required roles.
"""
def wrapper(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
perms = [Permission(RoleNeed(role)) for role in roles]
for perm in perms:
if not perm.can():
abort(HTTPStatus.FORBIDDEN)
return fn(*args, **kwargs)
return decorated_view
return wrapper
def roles_accepted(*roles):
"""Decorator which specifies that a user must have at least one of the
specified roles.
Aborts with HTTP: 403 if the user doesn't have at least one of the roles
Example::
@app.route('/create_post')
@roles_accepted('ROLE_ADMIN', 'ROLE_EDITOR')
def create_post():
return 'Create Post'
The current user must have either the `ROLE_ADMIN` role or `ROLE_EDITOR`
role in order to view the page.
:param args: The possible roles.
"""
def wrapper(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
perm = Permission(*[RoleNeed(role) for role in roles])
if not perm.can():
abort(HTTPStatus.FORBIDDEN)
return fn(*args, **kwargs)
return decorated_view
return wrapper
| {
"repo_name": "briancappello/flask-react-spa",
"path": "backend/security/decorators.py",
"copies": "1",
"size": "5953",
"license": "mit",
"hash": 2233047957083996700,
"line_mean": 33.2126436782,
"line_max": 103,
"alpha_frac": 0.6260708886,
"autogenerated": false,
"ratio": 4.0386702849389415,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00018292772914173553,
"num_lines": 174
} |
from functools import wraps
from http import HTTPStatus
from flask import current_app, request
from flask_restx import abort
from app.database import AuthTokens
from app.api.constants import AUTH_HEADER_KEY
class TokenRequiredMixin:
auth_methods = ['get', 'post', 'put', 'patch', 'delete']
auth_message = 'Authentication is required'
auth_http_code = HTTPStatus.UNAUTHORIZED
auth_token = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for auth_method in self.auth_methods:
method = getattr(self, auth_method, None)
if method:
setattr(self, auth_method, self._check_auth_token(method))
def _check_auth_token(self, function):
# FIXME: This a basic approach to verifying tokens, that's insecure especially
# without HTTPS, this needs to be replaced with a login based authentication
# and expiraing temporary tokens rather than constant ones, for better security.
@wraps(function)
def decorator(*args, **kwargs):
token = request.headers.get(AUTH_HEADER_KEY)
token_chunks = token.split(' ') if token else []
if len(token_chunks) > 1:
token = token_chunks[1]
self.auth_token = AuthTokens.get(token=token)
if not self.auth_token:
return abort(code=self.auth_http_code,
message=self.auth_message)
return function(*args, **kwargs)
return decorator
class GetOrRejectMixin:
gor_methods = ['get', 'put', 'patch', 'delete']
module = None
kwarg = ''
slug = ''
gor_message = ''
gor_http_code = HTTPStatus.NOT_FOUND
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.slug and self.kwarg:
self.slug = self.kwarg.split('_')[0]
if not self.gor_message and self.slug:
self.gor_message = f'{self.slug.title()} not found'
if self.module and self.kwarg:
for gor_method in self.gor_methods:
method = getattr(self, gor_method, None)
if method:
setattr(self, gor_method, self._get_or_reject(method))
def _get_or_reject(self, function):
@wraps(function)
def decorator(*args, **kwargs):
if self.module and self.kwarg:
kwarg = kwargs.get(self.kwarg)
if kwarg:
with current_app.app_context():
record = self.module.get(kwarg)
if not record:
abort(code=self.gor_http_code,
message=self.gor_message)
setattr(self, self.slug, record)
return function(*args, **kwargs)
return decorator
| {
"repo_name": "mrf345/FQM",
"path": "app/api/mixins.py",
"copies": "1",
"size": "2866",
"license": "mpl-2.0",
"hash": -7011488283458720000,
"line_mean": 31.5681818182,
"line_max": 88,
"alpha_frac": 0.5725750174,
"autogenerated": false,
"ratio": 4.177842565597667,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5250417582997667,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from httplib import FORBIDDEN, NOT_FOUND, INTERNAL_SERVER_ERROR, BAD_REQUEST
from django.http import JsonResponse
from django.views import defaults as default_views
from .constants import CSRF_INVALID
def csrf_failure(request, reason=''):
data = {
'error': True,
'err_msg': reason,
'err_code': CSRF_INVALID
}
return JsonResponse(data, safe=False, status=FORBIDDEN)
def add_json_support(default):
def deco(view):
@wraps(view)
def json_view(request, *args, **kwargs):
if 'application/json' in request.META['HTTP_ACCEPT']:
return view(request, *args, **kwargs)
return getattr(default_views, default)(request, *args, **kwargs)
return json_view
return deco
def create_error_handler(status, message):
return lambda *args, **kwargs: JsonResponse(
{'error': True, 'err_msg': message, 'err_code': -2}, safe=False, status=status)
api400 = add_json_support('bad_request')(create_error_handler(BAD_REQUEST, 'Bad request.'))
api403 = add_json_support('permission_denied')(create_error_handler(FORBIDDEN, 'Permission denied.'))
api404 = add_json_support('page_not_found')(create_error_handler(NOT_FOUND, 'Endpoint is not found.'))
api500 = add_json_support('server_error')(create_error_handler(INTERNAL_SERVER_ERROR, 'Internal server error.'))
| {
"repo_name": "zh012/djrest",
"path": "djrest/handlers.py",
"copies": "1",
"size": "1386",
"license": "mit",
"hash": -1679811391227548400,
"line_mean": 37.5,
"line_max": 112,
"alpha_frac": 0.6847041847,
"autogenerated": false,
"ratio": 3.6861702127659575,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48708743974659574,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from . import exceptions, http, application
from future.utils import with_metaclass
import re
def action(url, protection=None, authentication=False, method=None):
# url e.g: /<id>/action_name
def dec(func):
if protection:
func._protection_shield_method = protection
if authentication:
func._action_under_authentication = True
if method:
func._method_http = method.lower()
edit_url = url
if edit_url.startswith('/'): # remove the first /
edit_url = edit_url[1:]
pattern = re.search(r'\<(.*?)\>', url)
if pattern:
edit_url = edit_url.replace(pattern.group(), '#arg')
func._action_url = edit_url
@wraps(func)
def inner(*arg, **kw):
return func(*arg, **kw)
return inner
return dec
class RegisterActions(type):
def __new__(cls, name, bases, methods):
if '__model__' not in methods: # to pass the Action class
return type.__new__(cls, name, bases, methods)
model_class = methods['__model__']
for method_name, method in methods.items():
if not method_name.startswith('__'):
url = model_class._endpoint_url + '/' + method._action_url
application.add_action(url, method, name)
return type.__new__(cls, name, bases, methods)
class Action(with_metaclass(RegisterActions)):
def __init__(self, url=None, model_arg=None, request=None):
# url e.g: /api/user/123/action_name
# url e.g: /api/user/action_name
self.__request = request
if not model_arg:
self.action_url = http.param_at(url, 1) + '/' + http.param_at(url, -1) # e.g: 'user/action_name'
else:
self.action_url = http.param_at(url, 1) + '/#arg/' + http.param_at(url, -1) # e.g: 'user/123/action_name'
self.__model_arg = model_arg
self.__entire_url = url
self.__http_method = request.method.lower()
def process_action(self):
action_class = None
method = None
try:
method = application.get_action_method(self.action_url)
except:
raise exceptions.MethodNotFound()
action_class_name = application.get_action_class_name(self.action_url)
for clazz in Action.__subclasses__():
if clazz.__name__ == action_class_name:
action_class = clazz
break
authentication_class = application.get_authentication()
request_parameters = http.get_parameters(self.__request)
user_data = None
if authentication_class:
user_data = authentication_class.get_logged_user()
if hasattr(method, '_method_http'):
if method._method_http != self.__http_method:
raise exceptions.BadRequest()
if hasattr(method, '_protection_shield_method'):
shield_method = method._protection_shield_method
# shield returned False FIXME(improve tests)
if not shield_method(user_data, self.__model_arg, request_parameters):
raise exceptions.NotAuthorized()
if hasattr(method, '_action_under_authentication'):
if not user_data:
raise exceptions.ActionUnderAuthenticationProtection()
request_parameters = http.get_parameters(self.__request)
return method(action_class(self.__entire_url, None, self.__request), self.__model_arg, request_parameters)
| {
"repo_name": "felipevolpone/onhands",
"path": "ray-core/ray/actions.py",
"copies": "2",
"size": "3568",
"license": "mit",
"hash": -4439513001319933000,
"line_mean": 31.1441441441,
"line_max": 118,
"alpha_frac": 0.5880044843,
"autogenerated": false,
"ratio": 4.059158134243458,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5647162618543458,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from .. import Filter
from webob.exc import HTTPUnauthorized, HTTPForbidden
class AuthenticationProvider:
def __init__(self, ctx, request):
self.request = request
self.ctx = ctx
@property
def principal(self):
raise HTTPUnauthorized()
def has_permissions(self, permissions=None):
if self.principal is None:
raise HTTPUnauthorized()
if not permissions:
return True
if set(getattr(self.principal, 'roles', [])).intersection(permissions):
return True
raise HTTPForbidden()
class AuthenticationFilter(Filter):
def __init__(self, cls):
self.provider_cls = cls
def before_request(self, ctx, request):
request.security = self.provider_cls(ctx, request)
try:
request.principal = request.security.principal
except HTTPUnauthorized:
request.principal = None
return request
class Require:
def __init__(self, permissions=None, request=None):
self.request = request
self.permissions = permissions
def __call__(self, fn):
@wraps(fn)
def wrap(ctx, request):
if not getattr(request, 'security'):
raise HTTPUnauthorized()
if request.security.has_permissions(self.permissions):
return fn(ctx, request)
return wrap
def __enter__(self):
if not getattr(self.request, 'security'):
raise HTTPUnauthorized()
self.request.security.has_permissions(self.permissions)
def __exit__(self, exc_type, exc_val, exc_tb):
pass
| {
"repo_name": "comynli/m",
"path": "m/security/__init__.py",
"copies": "1",
"size": "1659",
"license": "apache-2.0",
"hash": -3214238680480046000,
"line_mean": 27.6034482759,
"line_max": 79,
"alpha_frac": 0.6154309825,
"autogenerated": false,
"ratio": 4.634078212290503,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5749509194790504,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from importlib import import_module
from puck.utils import fancy_import
from puck import stdlib
THINGS_TO_MONKEYPATCH = {
'puck.core.enebriate': '__builtin__.enumerate',
}
def patch_thing(source, target):
target_module_path, target_name = target.rsplit('.', 1)
target_module = __import__(target_module_path)
original = getattr(target_module, target_name)
setattr(target_module, target_name, wraps(original)(source))
return original
def unpatch_thing(target, original):
target_module_path, target_name = target.rsplit('.', 1)
target_module = import_module(target_module_path)
setattr(target_module, target_name, original)
class MonkeyPatcher(object):
def __init__(self, things_to_moneypatch=None):
if things_to_moneypatch is None:
things_to_moneypatch = THINGS_TO_MONKEYPATCH
self.things_to_moneypatch = things_to_moneypatch
self.registry = {}
def __enter__(self):
return self.monkeypatch()
def __exit__(self, exc_type, exc_val, exc_tb):
return self.unpatch()
def unpatch(self):
for target, original in self.registry.items():
unpatch_thing(target, original)
self.registry = {}
def monkeypatch(self):
for source, target in self.things_to_moneypatch.items():
if not stdlib.callable(source):
source = fancy_import(source)
self.registry[target] = patch_thing(source, target)
return self
def __call__(self):
return self
monkeypatcher = MonkeyPatcher()
| {
"repo_name": "pipermerriam/puck",
"path": "puck/chaos.py",
"copies": "1",
"size": "1599",
"license": "bsd-3-clause",
"hash": 984936212112260100,
"line_mean": 25.65,
"line_max": 64,
"alpha_frac": 0.6535334584,
"autogenerated": false,
"ratio": 3.780141843971631,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9931150049846379,
"avg_score": 0.000505050505050505,
"num_lines": 60
} |
from functools import wraps
from importlib import import_module
import os
import pkgutil
from threading import local
import warnings
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import cached_property
from django.utils.module_loading import import_by_path
from django.utils._os import upath
from django.utils import six
DEFAULT_DB_ALIAS = 'default'
class Error(Exception if six.PY3 else StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
class DataError(DatabaseError):
pass
class OperationalError(DatabaseError):
pass
class IntegrityError(DatabaseError):
pass
class InternalError(DatabaseError):
pass
class ProgrammingError(DatabaseError):
pass
class NotSupportedError(DatabaseError):
pass
class DatabaseErrorWrapper(object):
"""
Context manager and decorator that re-throws backend-specific database
exceptions using Django's common wrappers.
"""
def __init__(self, wrapper):
"""
wrapper is a database wrapper.
It must have a Database attribute defining PEP-249 exceptions.
"""
self.wrapper = wrapper
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
return
for dj_exc_type in (
DataError,
OperationalError,
IntegrityError,
InternalError,
ProgrammingError,
NotSupportedError,
DatabaseError,
InterfaceError,
Error,
):
db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__)
if issubclass(exc_type, db_exc_type):
dj_exc_value = dj_exc_type(*exc_value.args)
dj_exc_value.__cause__ = exc_value
# Only set the 'errors_occurred' flag for errors that may make
# the connection unusable.
if dj_exc_type not in (DataError, IntegrityError):
self.wrapper.errors_occurred = True
six.reraise(dj_exc_type, dj_exc_value, traceback)
def __call__(self, func):
# Note that we are intentionally not using @wraps here for performance
# reasons. Refs #21109.
def inner(*args, **kwargs):
with self:
return func(*args, **kwargs)
return inner
def load_backend(backend_name):
# Look for a fully qualified database backend name
try:
return import_module('%s.base' % backend_name)
except ImportError as e_user:
# The database backend wasn't found. Display a helpful error message
# listing all possible (built-in) database backends.
backend_dir = os.path.join(os.path.dirname(upath(__file__)), 'backends')
try:
builtin_backends = [
name for _, name, ispkg in pkgutil.iter_modules([backend_dir])
if ispkg and name != 'dummy']
except EnvironmentError:
builtin_backends = []
if backend_name not in ['django.db.backends.%s' % b for b in
builtin_backends]:
backend_reprs = map(repr, sorted(builtin_backends))
error_msg = ("%r isn't an available database backend.\n"
"Try using 'django.db.backends.XXX', where XXX "
"is one of:\n %s\nError was: %s" %
(backend_name, ", ".join(backend_reprs), e_user))
raise ImproperlyConfigured(error_msg)
else:
# If there's some other error, this must be an error in Django
raise
class ConnectionDoesNotExist(Exception):
pass
class ConnectionHandler(object):
def __init__(self, databases=None):
"""
databases is an optional dictionary of database definitions (structured
like settings.DATABASES).
"""
self._databases = databases
self._connections = local()
@cached_property
def databases(self):
if self._databases is None:
self._databases = settings.DATABASES
if self._databases == {}:
self._databases = {
DEFAULT_DB_ALIAS: {
'ENGINE': 'django.db.backends.dummy',
},
}
if DEFAULT_DB_ALIAS not in self._databases:
raise ImproperlyConfigured("You must define a '%s' database" % DEFAULT_DB_ALIAS)
return self._databases
def ensure_defaults(self, alias):
"""
Puts the defaults into the settings dictionary for a given connection
where no settings is provided.
"""
try:
conn = self.databases[alias]
except KeyError:
raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)
conn.setdefault('ATOMIC_REQUESTS', False)
if settings.TRANSACTIONS_MANAGED:
warnings.warn(
"TRANSACTIONS_MANAGED is deprecated. Use AUTOCOMMIT instead.",
DeprecationWarning, stacklevel=2)
conn.setdefault('AUTOCOMMIT', False)
conn.setdefault('AUTOCOMMIT', True)
conn.setdefault('ENGINE', 'django.db.backends.dummy')
if conn['ENGINE'] == 'django.db.backends.' or not conn['ENGINE']:
conn['ENGINE'] = 'django.db.backends.dummy'
conn.setdefault('CONN_MAX_AGE', 0)
conn.setdefault('OPTIONS', {})
conn.setdefault('TIME_ZONE', 'UTC' if settings.USE_TZ else settings.TIME_ZONE)
for setting in ['NAME', 'USER', 'PASSWORD', 'HOST', 'PORT']:
conn.setdefault(setting, '')
for setting in ['TEST_CHARSET', 'TEST_COLLATION', 'TEST_NAME', 'TEST_MIRROR']:
conn.setdefault(setting, None)
def __getitem__(self, alias):
if hasattr(self._connections, alias):
return getattr(self._connections, alias)
self.ensure_defaults(alias)
db = self.databases[alias]
backend = load_backend(db['ENGINE'])
conn = backend.DatabaseWrapper(db, alias)
setattr(self._connections, alias, conn)
return conn
def __setitem__(self, key, value):
setattr(self._connections, key, value)
def __delitem__(self, key):
delattr(self._connections, key)
def __iter__(self):
return iter(self.databases)
def all(self):
return [self[alias] for alias in self]
class ConnectionRouter(object):
def __init__(self, routers=None):
"""
If routers is not specified, will default to settings.DATABASE_ROUTERS.
"""
self._routers = routers
@cached_property
def routers(self):
if self._routers is None:
self._routers = settings.DATABASE_ROUTERS
routers = []
for r in self._routers:
if isinstance(r, six.string_types):
router = import_by_path(r)()
else:
router = r
routers.append(router)
return routers
def _router_func(action):
def _route_db(self, model, **hints):
chosen_db = None
for router in self.routers:
try:
method = getattr(router, action)
except AttributeError:
# If the router doesn't have a method, skip to the next one.
pass
else:
chosen_db = method(model, **hints)
if chosen_db:
return chosen_db
try:
return hints['instance']._state.db or DEFAULT_DB_ALIAS
except KeyError:
return DEFAULT_DB_ALIAS
return _route_db
db_for_read = _router_func('db_for_read')
db_for_write = _router_func('db_for_write')
def allow_relation(self, obj1, obj2, **hints):
for router in self.routers:
try:
method = router.allow_relation
except AttributeError:
# If the router doesn't have a method, skip to the next one.
pass
else:
allow = method(obj1, obj2, **hints)
if allow is not None:
return allow
return obj1._state.db == obj2._state.db
def allow_migrate(self, db, model):
for router in self.routers:
try:
try:
method = router.allow_migrate
except AttributeError:
method = router.allow_syncdb
except AttributeError:
# If the router doesn't have a method, skip to the next one.
pass
else:
allow = method(db, model)
if allow is not None:
return allow
return True
| {
"repo_name": "ar4s/django",
"path": "django/db/utils.py",
"copies": "3",
"size": "8960",
"license": "bsd-3-clause",
"hash": 4264144731435288600,
"line_mean": 31,
"line_max": 92,
"alpha_frac": 0.5690848214,
"autogenerated": false,
"ratio": 4.587813620071684,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0004892999304117479,
"num_lines": 280
} |
from functools import wraps
from importlib import reload
import boto3
from moto import mock_s3
from aws_etl_tools import config
from aws_etl_tools.guard import requires_s3_base_path
class MockS3Connection:
'''This is a decorator for mocking a connection to S3 for the life of a test. You can use it
in two ways: with and without a bucket. If a bucket is not specified, then at import time,
the decorator needs to know what bucket to mock, so it will pull it out of the config. So
there is coupling here. The easiest way to use this is to set the bucket in the initialization
of the decorator. If you want to be lazy on naming a bucket, then you'll
have to set an S3_BASE_PATH in the config.
'''
def __init__(self, bucket=None):
self.bucket = bucket or s3_bucket_name_from_config()
def __call__(self, function):
@wraps(function)
@mock_s3()
def with_mock_s3_connection(*args, **kwargs):
s3_connection = boto3.resource('s3')
s3_connection.create_bucket(Bucket=self.bucket)
return function(*args, **kwargs)
return with_mock_s3_connection
@requires_s3_base_path
def s3_bucket_name_from_config():
s3_base_path = reload(config).S3_BASE_PATH
bucket_name = s3_base_path.replace('s3://', '').split('/')[0]
return bucket_name
| {
"repo_name": "shopkeep/aws_etl_tools",
"path": "aws_etl_tools/mock_s3_connection.py",
"copies": "1",
"size": "1368",
"license": "apache-2.0",
"hash": 8627614991463557000,
"line_mean": 35,
"line_max": 102,
"alpha_frac": 0.6703216374,
"autogenerated": false,
"ratio": 3.619047619047619,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47893692564476187,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from inspect import getargspec
import argparse
import logging
import sys
from parse_this.core import (_check_types, _get_args_and_defaults,
_get_arg_parser, _get_args_to_parse, _call,
ParseThisError, Self, Class, FullHelpAction,
_call_method_from_namespace,
_get_parser_call_method, _get_parseable_methods)
__all__ = ["Self", "Class", "ParseThisError", "parse_this", "create_parser",
"parse_class"]
_LOG = logging.getLogger(__name__)
def parse_this(func, types, args=None, delimiter_chars=":"):
"""Create an ArgParser for the given function converting the command line
arguments according to the list of types.
Args:
func: the function for which the command line arguments to be parsed
types: a list of types - as accepted by argparse - that will be used to
convert the command line arguments
args: a list of arguments to be parsed if None sys.argv is used
delimiter_chars: characters used to separate the parameters from their
help message in the docstring. Defaults to ':'
"""
_LOG.debug("Creating parser for %s", func.__name__)
(func_args, dummy_1, dummy_2, defaults) = getargspec(func)
types, func_args = _check_types(func.__name__, types, func_args, defaults)
args_and_defaults = _get_args_and_defaults(func_args, defaults)
parser = _get_arg_parser(func, types, args_and_defaults, delimiter_chars)
arguments = parser.parse_args(_get_args_to_parse(args, sys.argv))
return _call(func, func_args, arguments)
class create_parser(object):
"""Creates an argument parser for the decorated function.
Note:
The method '__init__' can not be decorated if the class is not
decorated with 'parse_class'
"""
def __init__(self, *types, **options):
"""
Args:
types: vargs list of types to which the command line arguments
should be converted to
options: options to pass to create the parser. Possible values are:
-delimiter_chars: characters used to separate the parameters
from their help message in the docstring. Defaults to ':'
-name: name that will be used for the parser when used in a
class decorated with `parse_class`. If not provided the name
of the method will be used
"""
self._types = types
self._delimiter_chars = options.get("delimiter_chars", ":")
self._name = options.get("name", None)
def __call__(self, func):
"""Add an argument parser attribute `parser` to the decorated function.
Args:
func: the function for which we want to create an argument parser
"""
if not hasattr(func, "parser"):
_LOG.debug("Creating parser for '%s'%s", func.__name__,
"/%s" % self._name if self._name else "")
(func_args, _, _, defaults) = getargspec(func)
self._types, func_args = _check_types(func.__name__, self._types,
func_args, defaults)
args_and_defaults = _get_args_and_defaults(func_args, defaults)
parser = _get_arg_parser(func, self._types, args_and_defaults,
self._delimiter_chars)
parser.get_name = lambda: self._name
func.parser = parser
func.parser.call = _get_parser_call_method(func)
@wraps(func)
def decorated(*args, **kwargs):
return func(*args, **kwargs)
return decorated
class parse_class(object):
"""Allows to create a global argument parser for a class along with
subparsers with each if its properly decorated methods."""
def __init__(self, description=None, parse_private=False):
"""
Args:
description: give a specific description for the top level parser,
if not specified it will be the class docstring.
parse_private: specifies whether or not 'private' methods should be
parsed, defaults to False
"""
self._description = description
self._parse_private = parse_private
self._cls = None
def __call__(self, cls):
"""
Args:
cls: class to be decorated
"""
_LOG.debug("Creating parser for class '%s'", cls.__name__)
self._cls = cls
init_parser, methods_to_parse = _get_parseable_methods(cls)
self._set_class_parser(init_parser, methods_to_parse, cls)
return cls
def _add_sub_parsers(self, top_level_parser, methods_to_parse, class_name):
"""Add all the sub-parsers to the top_level_parser.
Args:
top_level_parser: the top level parser
methods_to_parse: dict of method name pointing to their associated
argument parser
class_name: name of the decorated class
Returns:
a dict of registered name of the parser i.e. sub command name
pointing to the method real name
"""
description = "Accessible methods of {}".format(class_name)
sub_parsers = top_level_parser.add_subparsers(description=description,
dest="method")
# Holds the mapping between the name registered for the parser
# and the method real name. It is useful in the 'inner_call'
# method retrieve the real method
parser_to_method = {}
for method_name, parser in methods_to_parse.items():
# We use the name provided in 'create_parser` or the name of the
# decorated method
parser_name = parser.get_name() or method_name
# Make the method name compatible for the argument parsing
if parser_name.startswith("_"):
if not self._parse_private:
# We skip private methods if the caller asked not to
# parse them
continue
# 'Private' methods are exposed without their leading or
# trailing '_'s. Also works for 'special' methods.
parser_name = parser_name.strip("_")
parser_name = parser_name.replace("_", "-")
parser_to_method[parser_name] = method_name
sub_parsers.add_parser(parser_name, parents=[parser],
add_help=False,
description=parser.description)
return parser_to_method
def _set_class_parser(self, init_parser, methods_to_parse, cls):
"""Creates the complete argument parser for the decorated class.
Args:
init_parser: argument parser for the __init__ method or None
methods_to_parse: dict of method name pointing to their associated
argument parser
cls: the class we are decorating
Returns:
The decorated class with an added attribute 'parser'
"""
top_level_parents = [init_parser] if init_parser else []
description = self._description or cls.__doc__
top_level_parser = argparse.ArgumentParser(description=description,
parents=top_level_parents,
add_help=False,
conflict_handler="resolve")
top_level_parser.add_argument("-h", "--help", action=FullHelpAction,
help="Display this help message")
parser_to_method = self._add_sub_parsers(top_level_parser,
methods_to_parse,
cls.__name__)
# Update the dict with the __init__ method so we can instantiate
# the decorated class
if init_parser:
parser_to_method["__init__"] = "__init__"
top_level_parser.call = self._get_parser_call_method(parser_to_method)
cls.parser = top_level_parser
def _get_parser_call_method(self, parser_to_method):
"""Return the parser special method 'call' that handles sub-command
calling.
Args:
parser_to_method: mapping of the parser registered name
to the method it is linked to
"""
def inner_call(args=None, instance=None):
"""Allows to call the method invoked from the command line or
provided argument.
Args:
args: list of arguments to parse, defaults to command line
arguments
instance: an instance of the decorated class. If instance is
None, the default, and __init__ is decorated the object will be
instantiated on the fly from the command line arguments
"""
parser = self._cls.parser
namespace = parser.parse_args(_get_args_to_parse(args, sys.argv))
if instance is None:
# If the __init__ method is not part of the method to
# decorate we cannot instantiate the class
if "__init__" not in parser_to_method:
raise ParseThisError(("'__init__' method is not decorated. "
"Please provide an instance to "
"'{}.parser.call' or decorate the "
"'__init___' method with "
"'create_parser'"
.format(self._cls.__name__)))
# We instantiate the class from the command line arguments
instance = _call_method_from_namespace(self._cls, "__init__",
namespace)
method_name = parser_to_method[namespace.method]
return _call_method_from_namespace(instance, method_name, namespace)
return inner_call
| {
"repo_name": "bertrandvidal/parse_this",
"path": "parse_this/__init__.py",
"copies": "1",
"size": "10214",
"license": "mit",
"hash": -8645865581441239000,
"line_mean": 44.3955555556,
"line_max": 80,
"alpha_frac": 0.5609947131,
"autogenerated": false,
"ratio": 4.772897196261682,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5833891909361683,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from inspect import getcallargs
from logging import getLogger
logger = getLogger(__name__)
class ValidationError(Exception):
def __init__(self, message):
self.message = message
class BaseArgValidator(object):
"""ArgValidatorの基底クラス。引数のバリデーションを行う。
使い方
1. 派生クラスでバリデーション対象の引数名に対応した clean_{xxx} を実装する
2. バリデーションエラーの場合、 ValidationError 例外を投げる
3. バリデーションに通過した場合、値を return する
.skip_args list バリデーションの対象外にする引数名のリスト
:Example:
>>> class ArgValidator(BaseArgValidator):
>>> skip_args = ['message']
>>>
>>> def clean_b(self, value):
>>> if value < 0:
>>> raise ValidationError("b must be greater than equal 0")
>>>
>>> return value * 2
>>>
>>> @register_arg_validator(ArgValidator)
>>> def huga(b):
>>> print("0 <= {}", b)
"""
skip_args = []
def __init__(self, callargs, extras=[]):
"""__init__
:param Dict[str, Any] callargs: 引数名と値の辞書
:param List[str] extras:
呼び出し時の引数になくてもバリデーションする追加フィールド。
引数で受け取ったidでdbへ存在チェックし、
結果を引数で渡すような場面で使う。
"""
self.callargs = callargs
self.extras = extras
self.cleaned_data = {}
self.errors = {}
def handle_errors(self):
"""バリデーションに失敗した時呼び出されるハンドラ
オーバーライドして使う
"""
pass
def is_valid(self):
"""バリデーションの実行
:return bool: valid or not
"""
self.cleaned_data = {}
self.errors = {}
for name, given in self.callargs.items():
# .skip_args の変数は検証しない
if name in self.skip_args + self.extras:
self.cleaned_data[name] = given
continue
# clean_xxx メソッドがある場合は呼び出して検証
f = getattr(self, 'clean_{}'.format(name), None)
if not f or not callable(f):
self.cleaned_data[name] = given
logger.debug("do not have clean_%s method", name)
continue
try:
self.cleaned_data[name] = f(given)
except ValidationError as e:
self.errors[name] = e.message
# 追加フィールドの検証
for extra_name in self.extras:
f = getattr(self, 'clean_{}'.format(extra_name))
try:
self.cleaned_data[extra_name] = f()
except ValidationError as e:
self.errors[extra_name] = e.message
return not self.errors
def register_arg_validator(cls, extras=[]):
"""関数にバリデータを追加する
.. note::
- デコレートする関数は可変長の引数をつかえません
- デコレートする関数への引数の渡し方は現状の実装では
呼び出し時と一致しません
:param BaesArgValidator cls: バリデータのクラス
"""
assert issubclass(cls, BaseArgValidator)
def _inner(func):
@wraps(func)
def wrapper(*args, **kwargs):
callargs = getcallargs(func, *args, **kwargs)
validator = cls(callargs, extras)
if not validator.is_valid():
validator.handle_errors()
return
# XXX ここほんとはポジショナル引数でわたせたほうがいいのかな
return func(**validator.cleaned_data)
return wrapper
return _inner
| {
"repo_name": "beproud/beproudbot",
"path": "src/haro/arg_validator.py",
"copies": "1",
"size": "3972",
"license": "mit",
"hash": 1862300806025457700,
"line_mean": 23.976744186,
"line_max": 75,
"alpha_frac": 0.5518311608,
"autogenerated": false,
"ratio": 2.5470355731225296,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.359886673392253,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from inspect import getmembers, isfunction
from webob import exc
import six
from .decorators import expose
from .util import _cfg, iscontroller
__all__ = ['unlocked', 'secure', 'SecureController']
if six.PY3:
from .compat import is_bound_method as ismethod
else:
from inspect import ismethod
class _SecureState(object):
def __init__(self, desc, boolean_value):
self.description = desc
self.boolean_value = boolean_value
def __repr__(self):
return '<SecureState %s>' % self.description
def __nonzero__(self):
return self.boolean_value
def __bool__(self):
return self.__nonzero__()
Any = _SecureState('Any', False)
Protected = _SecureState('Protected', True)
# security method decorators
def _unlocked_method(func):
_cfg(func)['secured'] = Any
return func
def _secure_method(check_permissions_func):
def wrap(func):
cfg = _cfg(func)
cfg['secured'] = Protected
cfg['check_permissions'] = check_permissions_func
return func
return wrap
# classes to assist with wrapping attributes
class _UnlockedAttribute(object):
def __init__(self, obj):
self.obj = obj
@_unlocked_method
@expose()
def _lookup(self, *remainder):
return self.obj, remainder
class _SecuredAttribute(object):
def __init__(self, obj, check_permissions):
self.obj = obj
self.check_permissions = check_permissions
self._parent = None
def _check_permissions(self):
if isinstance(self.check_permissions, six.string_types):
return getattr(self.parent, self.check_permissions)()
else:
return self.check_permissions()
def __get_parent(self):
return self._parent
def __set_parent(self, parent):
if ismethod(parent):
self._parent = six.get_method_self(parent)
else:
self._parent = parent
parent = property(__get_parent, __set_parent)
@_secure_method('_check_permissions')
@expose()
def _lookup(self, *remainder):
return self.obj, list(remainder)
# helper for secure decorator
def _allowed_check_permissions_types(x):
return (
ismethod(x) or
isfunction(x) or
isinstance(x, six.string_types)
)
# methods that can either decorate functions or wrap classes
# these should be the main methods used for securing or unlocking
def unlocked(func_or_obj):
"""
This method unlocks method or class attribute on a SecureController. Can
be used to decorate or wrap an attribute
"""
if ismethod(func_or_obj) or isfunction(func_or_obj):
return _unlocked_method(func_or_obj)
else:
return _UnlockedAttribute(func_or_obj)
def secure(func_or_obj, check_permissions_for_obj=None):
"""
This method secures a method or class depending on invocation.
To decorate a method use one argument:
@secure(<check_permissions_method>)
To secure a class, invoke with two arguments:
secure(<obj instance>, <check_permissions_method>)
"""
if _allowed_check_permissions_types(func_or_obj):
return _secure_method(func_or_obj)
else:
if not _allowed_check_permissions_types(check_permissions_for_obj):
msg = "When securing an object, secure() requires the " + \
"second argument to be method"
raise TypeError(msg)
return _SecuredAttribute(func_or_obj, check_permissions_for_obj)
class SecureControllerMeta(type):
"""
Used to apply security to a controller.
Implementations of SecureController should extend the
`check_permissions` method to return a True or False
value (depending on whether or not the user has permissions
to the controller).
"""
def __init__(cls, name, bases, dict_):
cls._pecan = dict(
secured=Protected,
check_permissions=cls.check_permissions,
unlocked=[]
)
for name, value in getmembers(cls)[:]:
if (isfunction if six.PY3 else ismethod)(value):
if iscontroller(value) and value._pecan.get(
'secured'
) is None:
# Wrap the function so that the security context is
# local to this class definition. This works around
# the fact that unbound method attributes are shared
# across classes with the same bases.
wrapped = _make_wrapper(value)
wrapped._pecan['secured'] = Protected
wrapped._pecan['check_permissions'] = \
cls.check_permissions
setattr(cls, name, wrapped)
elif hasattr(value, '__class__'):
if name.startswith('__') and name.endswith('__'):
continue
if isinstance(value, _UnlockedAttribute):
# mark it as unlocked and remove wrapper
cls._pecan['unlocked'].append(value.obj)
setattr(cls, name, value.obj)
elif isinstance(value, _SecuredAttribute):
# The user has specified a different check_permissions
# than the class level version. As far as the class
# is concerned, this method is unlocked because
# it is using a check_permissions function embedded in
# the _SecuredAttribute wrapper
cls._pecan['unlocked'].append(value)
class SecureControllerBase(object):
@classmethod
def check_permissions(cls):
"""
Returns `True` or `False` to grant access. Implemented in subclasses
of :class:`SecureController`.
"""
return False
SecureController = SecureControllerMeta(
'SecureController',
(SecureControllerBase,),
{'__doc__': SecureControllerMeta.__doc__}
)
def _make_wrapper(f):
"""return a wrapped function with a copy of the _pecan context"""
@wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
wrapper._pecan = f._pecan.copy()
return wrapper
# methods to evaluate security during routing
def handle_security(controller, im_self=None):
""" Checks the security of a controller. """
if controller._pecan.get('secured', False):
check_permissions = controller._pecan['check_permissions']
if isinstance(check_permissions, six.string_types):
check_permissions = getattr(
im_self or six.get_method_self(controller),
check_permissions
)
if not check_permissions():
raise exc.HTTPUnauthorized
def cross_boundary(prev_obj, obj):
""" Check permissions as we move between object instances. """
if prev_obj is None:
return
if isinstance(obj, _SecuredAttribute):
# a secure attribute can live in unsecure class so we have to set
# while we walk the route
obj.parent = prev_obj
if hasattr(prev_obj, '_pecan'):
if obj not in prev_obj._pecan.get('unlocked', []):
handle_security(prev_obj)
| {
"repo_name": "pecan/pecan",
"path": "pecan/secure.py",
"copies": "2",
"size": "7242",
"license": "bsd-3-clause",
"hash": 8602843068564160000,
"line_mean": 30.2155172414,
"line_max": 77,
"alpha_frac": 0.6121237227,
"autogenerated": false,
"ratio": 4.3081499107674,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00013061650992685477,
"num_lines": 232
} |
from functools import wraps
from inspect import getmembers, isfunction
from webob import exc
import six
if six.PY3:
from .compat import is_bound_method as ismethod
else:
from inspect import ismethod
from .decorators import expose
from .util import _cfg, iscontroller
__all__ = ['unlocked', 'secure', 'SecureController']
class _SecureState(object):
def __init__(self, desc, boolean_value):
self.description = desc
self.boolean_value = boolean_value
def __repr__(self):
return '<SecureState %s>' % self.description
def __nonzero__(self):
return self.boolean_value
def __bool__(self):
return self.__nonzero__()
Any = _SecureState('Any', False)
Protected = _SecureState('Protected', True)
# security method decorators
def _unlocked_method(func):
_cfg(func)['secured'] = Any
return func
def _secure_method(check_permissions_func):
def wrap(func):
cfg = _cfg(func)
cfg['secured'] = Protected
cfg['check_permissions'] = check_permissions_func
return func
return wrap
# classes to assist with wrapping attributes
class _UnlockedAttribute(object):
def __init__(self, obj):
self.obj = obj
@_unlocked_method
@expose()
def _lookup(self, *remainder):
return self.obj, remainder
class _SecuredAttribute(object):
def __init__(self, obj, check_permissions):
self.obj = obj
self.check_permissions = check_permissions
self._parent = None
def _check_permissions(self):
if isinstance(self.check_permissions, six.string_types):
return getattr(self.parent, self.check_permissions)()
else:
return self.check_permissions()
def __get_parent(self):
return self._parent
def __set_parent(self, parent):
if ismethod(parent):
self._parent = six.get_method_self(parent)
else:
self._parent = parent
parent = property(__get_parent, __set_parent)
@_secure_method('_check_permissions')
@expose()
def _lookup(self, *remainder):
return self.obj, remainder
# helper for secure decorator
def _allowed_check_permissions_types(x):
return (
ismethod(x) or
isfunction(x) or
isinstance(x, six.string_types)
)
# methods that can either decorate functions or wrap classes
# these should be the main methods used for securing or unlocking
def unlocked(func_or_obj):
"""
This method unlocks method or class attribute on a SecureController. Can
be used to decorate or wrap an attribute
"""
if ismethod(func_or_obj) or isfunction(func_or_obj):
return _unlocked_method(func_or_obj)
else:
return _UnlockedAttribute(func_or_obj)
def secure(func_or_obj, check_permissions_for_obj=None):
"""
This method secures a method or class depending on invocation.
To decorate a method use one argument:
@secure(<check_permissions_method>)
To secure a class, invoke with two arguments:
secure(<obj instance>, <check_permissions_method>)
"""
if _allowed_check_permissions_types(func_or_obj):
return _secure_method(func_or_obj)
else:
if not _allowed_check_permissions_types(check_permissions_for_obj):
msg = "When securing an object, secure() requires the " + \
"second argument to be method"
raise TypeError(msg)
return _SecuredAttribute(func_or_obj, check_permissions_for_obj)
class SecureControllerMeta(type):
"""
Used to apply security to a controller.
Implementations of SecureController should extend the
`check_permissions` method to return a True or False
value (depending on whether or not the user has permissions
to the controller).
"""
def __init__(cls, name, bases, dict_):
cls._pecan = dict(
secured=Protected,
check_permissions=cls.check_permissions,
unlocked=[]
)
for name, value in getmembers(cls)[:]:
if (isfunction if six.PY3 else ismethod)(value):
if iscontroller(value) and value._pecan.get(
'secured'
) is None:
# Wrap the function so that the security context is
# local to this class definition. This works around
# the fact that unbound method attributes are shared
# across classes with the same bases.
wrapped = _make_wrapper(value)
wrapped._pecan['secured'] = Protected
wrapped._pecan['check_permissions'] = \
cls.check_permissions
setattr(cls, name, wrapped)
elif hasattr(value, '__class__'):
if name.startswith('__') and name.endswith('__'):
continue
if isinstance(value, _UnlockedAttribute):
# mark it as unlocked and remove wrapper
cls._pecan['unlocked'].append(value.obj)
setattr(cls, name, value.obj)
elif isinstance(value, _SecuredAttribute):
# The user has specified a different check_permissions
# than the class level version. As far as the class
# is concerned, this method is unlocked because
# it is using a check_permissions function embedded in
# the _SecuredAttribute wrapper
cls._pecan['unlocked'].append(value)
class SecureControllerBase(object):
@classmethod
def check_permissions(cls):
return False
SecureController = SecureControllerMeta(
'SecureController',
(SecureControllerBase,),
{}
)
def _make_wrapper(f):
"""return a wrapped function with a copy of the _pecan context"""
@wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
wrapper._pecan = f._pecan.copy()
return wrapper
# methods to evaluate security during routing
def handle_security(controller):
""" Checks the security of a controller. """
if controller._pecan.get('secured', False):
check_permissions = controller._pecan['check_permissions']
if isinstance(check_permissions, six.string_types):
check_permissions = getattr(
six.get_method_self(controller),
check_permissions
)
if not check_permissions():
raise exc.HTTPUnauthorized
def cross_boundary(prev_obj, obj):
""" Check permissions as we move between object instances. """
if prev_obj is None:
return
if isinstance(obj, _SecuredAttribute):
# a secure attribute can live in unsecure class so we have to set
# while we walk the route
obj.parent = prev_obj
if hasattr(prev_obj, '_pecan'):
if obj not in prev_obj._pecan.get('unlocked', []):
handle_security(prev_obj)
| {
"repo_name": "citrix-openstack-build/pecan",
"path": "pecan/secure.py",
"copies": "1",
"size": "7033",
"license": "bsd-3-clause",
"hash": -2972380329412463000,
"line_mean": 29.711790393,
"line_max": 77,
"alpha_frac": 0.6125408787,
"autogenerated": false,
"ratio": 4.32002457002457,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.543256544872457,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from inspect import signature, _empty, isclass, getmro
from .core import validate
def validate_fn(validator=None, on_failure=None, vctx=None):
def decorator(fn):
@wraps(fn)
def inner_fn(*args, **kwargs):
vresult = _validate_fn_params(fn, validator, vctx, *args, **kwargs)
if vresult.success:
return fn(*args, **kwargs)
else:
return _handle_on_failure(vresult, on_failure, fn, *args, **kwargs)
return inner_fn
return decorator
def _annotation_is_validator(param):
return param.annotation is not _empty and \
(callable(param.annotation) or isinstance(param.annotation, (tuple, list)))
def _validate_fn_params(fn, validator=None, vctx=None, *args, **kwargs):
sig = signature(fn)
ba = sig.bind(*args, **kwargs)
va = []
for param in sig.parameters.values():
if param.name not in ba.arguments:
ba.arguments[param.name] = param.default
if _annotation_is_validator(param) and ba.arguments[param.name] != param.default:
# validate only if called with not the default value
va.append((
param.name, # selector
param.annotation # validation rules
))
if validator is not None:
va = va + list(validator)
return validate(va, ba.arguments, ctx=vctx)
def _handle_on_failure(vresult, on_failure, fn, *args, **kwargs):
if isclass(on_failure):
if Exception in getmro(on_failure):
raise on_failure(vresult)
else:
return on_failure(vresult=vresult)
elif callable(on_failure):
return on_failure(vresult)
elif on_failure is None:
return fn(*args, **kwargs)
| {
"repo_name": "YaraslauZhylko/gladiator",
"path": "gladiator/decorators.py",
"copies": "2",
"size": "1780",
"license": "bsd-3-clause",
"hash": -4088888432393724400,
"line_mean": 33.2307692308,
"line_max": 89,
"alpha_frac": 0.6151685393,
"autogenerated": false,
"ratio": 3.827956989247312,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5443125528547312,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from inspect import signature
from .container import IOCContainer
_container = IOCContainer()
def _get_filled_arguments(func, *args, **kwargs):
function_signature = signature(func)
ba = function_signature.bind_partial(*args, **kwargs)
return ba.arguments
def inject(**dec_kwargs):
def _wrapper_f(f):
@wraps(f)
def _wrapper(*args, **kwargs):
filled_arguments = _get_filled_arguments(f, *args, **kwargs)
for arg_name, cls in dec_kwargs.items():
if arg_name not in filled_arguments:
kwargs[arg_name] = _container.get_instance(cls)
return f(*args, **kwargs)
return _wrapper
return _wrapper_f
def inject_value(**dec_kwargs):
def _wrapper_f(f):
@wraps(f)
def _wrapper(*args, **kwargs):
filled_arguments = _get_filled_arguments(f, *args, **kwargs)
for arg_name, val in dec_kwargs.items():
if arg_name not in filled_arguments:
kwargs[arg_name] = val
return f(*args, **kwargs)
return _wrapper
return _wrapper_f
| {
"repo_name": "MichalPodeszwa/pySyringe",
"path": "pysyringe/injector.py",
"copies": "1",
"size": "1170",
"license": "mit",
"hash": -8239291066462906000,
"line_mean": 22.4,
"line_max": 72,
"alpha_frac": 0.5854700855,
"autogenerated": false,
"ratio": 3.9130434782608696,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49985135637608696,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from inspect import signature
from IPython.display import display
import matplotlib.pylab as plt
import sympy as sp
#
# General
#
def disallow_none_kwargs(f):
required_kwargs = []
for param in signature(f).parameters.values():
if param.default is None:
required_kwargs.append(param.name)
@wraps(f)
def wrapper(*args, **kwargs):
for kwarg in required_kwargs:
if kwarg not in kwargs:
raise Exception(f"Keyword argument {kwarg} is required.")
return f(*args, **kwargs)
return wrapper
def stringify(value):
if isinstance(value, float):
return str(value if not value.is_integer() else int(value))
else:
return str(value)
def pp_table(table, v_sep='|', h_sep='-', cross_sep='+'):
just = []
for key, col in table.items():
just.append(max(len(stringify(key)), *(len(stringify(cell)) for cell in col)))
print(f" {v_sep} ".join(header.ljust(just[i]) for i, header in enumerate(table.keys())))
print(f"{h_sep}{cross_sep}{h_sep}".join(h_sep*just[i] for i, _ in enumerate(table.keys())))
for row in zip(*table.values()):
print(f" {v_sep} ".join(stringify(cell).ljust(just[i]) for i, cell in enumerate(row)))
def group_dicts(dicts):
iterable = iter(dicts)
head = next(iterable)
keys = head.keys()
result = {key: [] for key in keys}
for key, value in head.items():
result[key].append(value)
for dict in iterable:
assert dict.keys() == keys, "Dictionaries must have same shape"
for key, value in dict.items():
result[key].append(value)
return result
def pp(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
pp_table(group_dicts(fn(*args, **kwargs)))
return wrapper
def with_error(results, y, x_key='x', y_key='y'):
for result in results:
y_i = y(result[x_key])
yield {**result, "error": abs(y_i - result[y_key]), 'exact': y_i}
#
# ODE, Euler
#
def ivp(expr, x, ivs):
eqs = (sp.Eq(expr.subs(x, iv[0]), iv[1]) for iv in ivs)
free_symbols_solutions = sp.solve(eqs, dict=True)
if len(free_symbols_solutions) == 0:
raise Exception(f"Free symbols in expr has no solutions")
elif len(free_symbols_solutions) > 1:
raise Exception(f"Free symbols in expr has multiple solutions\n{list(free_symbols_solutions)}")
return expr.subs(free_symbols_solutions[0])
def euler_normal(f, h, t):
return lambda w, i: w + h * f(t(i-1), w)
def euler_trapezoid(f, h, t):
def trapezoid(w, i):
t_i = t(i-1)
w_n = f(t_i, w)
return w + h*(w_n + f(t_i+h, w + h*w_n))/2
return trapezoid
def euler_midpoint(f, h, t):
def midpoint(w, i):
t_i = t(i-1)
w_n = f(t_i, w)
return w + h*f(t_i+h/2, w + h*w_n/2)
return midpoint
def euler_rk4(f, h, t):
def rk4(w, i):
t_i = t(i-1)
s1 = f(t_i, w)
s2 = f(t_i + (h / 2), w + (h / 2) * s1)
s3 = f(t_i + (h / 2), w + (h / 2) * s2)
s4 = f(t_i + h, w + h * s3)
return w + (h / 6) * (s1 + 2 * s2 + 2 * s3 + s4)
return rk4
@disallow_none_kwargs
def euler(f, h=1, t=None, iv=None, method=euler_normal):
fro, to = iv[0], t
n = (to - fro) / h
if not (n.is_integer() and n > 0):
raise Exception("Number of iterations must be a positive integer.")
n = int(n)
t_i = lambda i: fro + i/(1/h) # Trying to avoid floating point rounding errors
step = method(f, h, t_i)
w = iv[1]
yield dict(i=0, t=t_i(0), w=iv[1])
for i in range(1, n+1):
w = step(w, i)
yield dict(i=i, t=t_i(i), w=w)
@disallow_none_kwargs
def euler_error(f, iv=None, multiple_eqs_strategy=lambda eqs: eqs[0], **kwargs):
y = sp.Function('y')
t = sp.Symbol('t')
y_d = sp.Eq(y(t).diff(t), f(t, y(t)))
diff_eq = sp.dsolve(y_d)
if isinstance(diff_eq, list):
diff_eq = multiple_eqs_strategy(diff_eq)
exact = ivp(diff_eq.rhs, t, [iv])
display(y_d)
display(sp.Eq(y(t), exact))
y_fn = sp.lambdify(t, exact)
return with_error(euler(f, iv=iv, **kwargs), y_fn, x_key='t', y_key='w')
def plot(results, exact_key='exact', estimate_key='y', x_key='x'):
w = []
y = []
t = []
for result in results:
w.append(result[estimate_key])
y.append(result[exact_key])
t.append(result[x_key])
plt.plot(t, w)
plt.plot(t, y)
def plot_gen(results, y_keys=None, x_keys=None):
ys = [[] for _ in y_keys]
xs = [[] for _ in x_keys]
for result in results:
for key, y in zip(y_keys, ys):
y.append(result[key])
for key, x in zip(x_keys, xs):
x.append(result[key])
for y, x in zip(ys, xs):
plt.plot(x, y)
def body3(y, m1, m2, m3, g):
return sp.Matrix([
y[1],
(g * m2 * (y[4] - y[0])) / ((y[4] - y[0]) ** 2 + (y[6] - y[2]) ** 2) ** (3 / 2) + (g * m3 * (y[8] - y[0])) / (
(y[8] - y[0]) ** 2 + (y[10] - y[2]) ** 2) ** (3 / 2),
y[3],
(g * m2 * (y[6] - y[2])) / ((y[4] - y[0]) ** 2 + (y[6] - y[2]) ** 2) ** (3 / 2) + (g * m3 * (y[10] - y[2])) / (
(y[8] - y[0]) ** 2 + (y[10] - y[2]) ** 2) ** (3 / 2),
y[5],
(g * m1 * (y[0] - y[4])) / ((y[0] - y[4]) ** 2 + (y[2] - y[6]) ** 2) ** (3 / 2) + (g * m3 * (y[8] - y[4])) / (
(y[8] - y[4]) ** 2 + (y[10] - y[6]) ** 2) ** (3 / 2),
y[7],
(g * m1 * (y[2] - y[6])) / ((y[0] - y[4]) ** 2 + (y[2] - y[6]) ** 2) ** (3 / 2) + (g * m3 * (y[10] - y[6])) / (
(y[8] - y[4]) ** 2 + (y[10] - y[6]) ** 2) ** (3 / 2),
y[9],
(g * m2 * (y[4] - y[8])) / ((y[4] - y[8]) ** 2 + (y[6] - y[10]) ** 2) ** (3 / 2) + (g * m1 * (y[0] - y[8])) / (
(y[0] - y[8]) ** 2 + (y[2] - y[10]) ** 2) ** (3 / 2),
y[11],
(g * m2 * (y[6] - y[10])) / ((y[4] - y[8]) ** 2 + (y[6] - y[10]) ** 2) ** (3 / 2) + (g * m1 * (y[2] - y[10])) / (
(y[0] - y[8]) ** 2 + (y[2] - y[10]) ** 2) ** (3 / 2)
])
def body3_y():
x1, y1, v1x, v1y = sp.symbols("x_1 y_1 v_1_x v_1_y")
x2, y2, v2x, v2y = sp.symbols("x_2 y_2 v_2_x v_2_y")
x3, y3, v3x, v3y = sp.symbols("x_3 y_3 v_3_x v_3_y")
return sp.Matrix([x1, v1x, y1, v1y, x2, v2x, y2, v2y, x3, v3x, y3, v3y])
def body3_iv(b1, v1, b2, v2, b3, v3):
return sp.Matrix([b1[0], v1[0], b1[1], v1[1], b2[0], v2[0], b2[1], v2[1], b3[0], v3[0], b3[1], v3[1]])
| {
"repo_name": "regiontog/matte3",
"path": "common/__init__.py",
"copies": "1",
"size": "6469",
"license": "mit",
"hash": 5678344073019216000,
"line_mean": 26.6452991453,
"line_max": 121,
"alpha_frac": 0.495130623,
"autogenerated": false,
"ratio": 2.462504758279406,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.34576353812794064,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from inspect import signature
import warnings
def deprecate_param(version_removed, parameter_name, *additional_names):
"""Create a decorator which warns of parameter deprecation
Use this to create a decorator which will watch for use of a
deprecated parameter and issue a ``FutureWarning`` if the parameter
is used. (Use a ``FutureWarning`` because Python does not display
``DeprecationWarning`` by default.) The decorator introspects the
wrapped function's signature so that it catches both keyword
and positional argument use. The default value of the parameter
will not be affected.
Parameters
----------
version_removed: str
The version in which this parameter will no longer be an allowed
input to the function, e.g. "v2.0.0".
parameter_name: str
The name of the parameter to be deprecated, as it appears in the
function signature.
*additional_names
Use additional positional arguments to indicate multiple parameters
to deprecate.
Returns
-------
A decorator function
Raises
------
ValueError
If the named parameter is not
an argument of the wrapped function
Examples
--------
>>> @deprecate_param('v2.0.0', 'param2')
... def adder(param1, param2=0, param3=0):
... return param1 + param2 + param3
>>> adder(1, 2, 3)
/Users/username/src/civis-python/civis/utils/deprecation.py:68:
FutureWarning: The "param2" parameter of "__main__.adder" is deprecated
and will be removed in v2.0.0.
FutureWarning)
6
>>> adder(1, param3=13)
14
"""
all_names = [parameter_name] + list(additional_names)
def decorator(func):
# Introspect the wrapped function so that we can find
# where the parameter is in the order of the function's inputs.
# Signature.parameters is a subclass of OrderedDict.
sig = signature(func)
i_args = []
for name in all_names:
if name not in sig.parameters:
raise ValueError('"{}" is not a parameter of '
'{}.'.format(parameter_name, str(func)))
i_args.append(list(sig.parameters.keys()).index(parameter_name))
@wraps(func)
def wrapper(*args, **kwargs):
warn_list = []
for name, i_arg in zip(all_names, i_args):
# The len(args) check looks to see if the user has tried
# to call the deprecated parameter as a positional argument.
if len(args) > i_arg or name in kwargs:
f_name = '{}.{}'.format(func.__module__, func.__name__)
msg = ('The "{}" parameter of "{}" is deprecated and '
'will be removed in {}.'.format(name,
f_name,
version_removed))
warn_list.append(msg)
if warn_list:
warnings.warn('\n'.join(warn_list), FutureWarning)
return func(*args, **kwargs)
return wrapper
return decorator
| {
"repo_name": "civisanalytics/civis-python",
"path": "civis/_deprecation.py",
"copies": "1",
"size": "3219",
"license": "bsd-3-clause",
"hash": -162660110060183580,
"line_mean": 37.3214285714,
"line_max": 76,
"alpha_frac": 0.5840323082,
"autogenerated": false,
"ratio": 4.578947368421052,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5662979676621053,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from inspect import signature, Parameter
from types import FunctionType
from .utils import is_iterable, comma_join, NO_VALUE, arg_to_sql
from .query import Cond, QuerySet
def binary_operator(func):
"""
Decorates a function to mark it as a binary operator.
"""
@wraps(func)
def wrapper(*args, **kwargs):
ret = func(*args, **kwargs)
ret.is_binary_operator = True
return ret
return wrapper
def type_conversion(func):
"""
Decorates a function to mark it as a type conversion function.
The metaclass automatically generates "OrZero" and "OrNull" combinators
for the decorated function.
"""
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper.f_type = 'type_conversion'
return wrapper
def aggregate(func):
"""
Decorates a function to mark it as an aggregate function.
The metaclass automatically generates combinators such as "OrDefault",
"OrNull", "If" etc. for the decorated function.
"""
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper.f_type = 'aggregate'
return wrapper
def with_utf8_support(func):
"""
Decorates a function to mark it as a string function that has a UTF8 variant.
The metaclass automatically generates a "UTF8" combinator for the decorated function.
"""
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper.f_type = 'with_utf8_support'
return wrapper
def parametric(func):
"""
Decorates a function to convert it to a parametric function, such
as `quantile(level)(expr)`.
"""
@wraps(func)
def wrapper(*parameters):
@wraps(func)
def inner(*args, **kwargs):
f = func(*args, **kwargs)
# Append the parameter to the function name
parameters_str = comma_join(parameters, stringify=True)
f.name = '%s(%s)' % (f.name, parameters_str)
return f
return inner
wrapper.f_parametric = True
return wrapper
class FunctionOperatorsMixin(object):
"""
A mixin for implementing Python operators using F objects.
"""
# Comparison operators
def __lt__(self, other):
return F.less(self, other)
def __le__(self, other):
return F.lessOrEquals(self, other)
def __eq__(self, other):
return F.equals(self, other)
def __ne__(self, other):
return F.notEquals(self, other)
def __gt__(self, other):
return F.greater(self, other)
def __ge__(self, other):
return F.greaterOrEquals(self, other)
# Arithmetic operators
def __add__(self, other):
return F.plus(self, other)
def __radd__(self, other):
return F.plus(other, self)
def __sub__(self, other):
return F.minus(self, other)
def __rsub__(self, other):
return F.minus(other, self)
def __mul__(self, other):
return F.multiply(self, other)
def __rmul__(self, other):
return F.multiply(other, self)
def __truediv__(self, other):
return F.divide(self, other)
def __rtruediv__(self, other):
return F.divide(other, self)
def __floordiv__(self, other):
return F.intDiv(self, other)
def __rfloordiv__(self, other):
return F.intDiv(other, self)
def __mod__(self, other):
return F.modulo(self, other)
def __rmod__(self, other):
return F.modulo(other, self)
def __neg__(self):
return F.negate(self)
def __pos__(self):
return self
# Logical operators
def __and__(self, other):
return F._and(self, other)
def __rand__(self, other):
return F._and(other, self)
def __or__(self, other):
return F._or(self, other)
def __ror__(self, other):
return F._or(other, self)
def __xor__(self, other):
return F._xor(self, other)
def __rxor__(self, other):
return F._xor(other, self)
def __invert__(self):
return F._not(self)
def isIn(self, others):
return F._in(self, others)
def isNotIn(self, others):
return F._notIn(self, others)
class FMeta(type):
FUNCTION_COMBINATORS = {
'type_conversion': [
{'suffix': 'OrZero'},
{'suffix': 'OrNull'},
],
'aggregate': [
{'suffix': 'OrDefault'},
{'suffix': 'OrNull'},
{'suffix': 'If', 'args': ['cond']},
{'suffix': 'OrDefaultIf', 'args': ['cond']},
{'suffix': 'OrNullIf', 'args': ['cond']},
],
'with_utf8_support': [
{'suffix': 'UTF8'},
]
}
def __init__(cls, name, bases, dct):
for name, obj in dct.items():
if hasattr(obj, '__func__'):
f_type = getattr(obj.__func__, 'f_type', '')
for combinator in FMeta.FUNCTION_COMBINATORS.get(f_type, []):
new_name = name + combinator['suffix']
FMeta._add_func(cls, obj.__func__, new_name, combinator.get('args'))
@staticmethod
def _add_func(cls, base_func, new_name, extra_args):
"""
Adds a new func to the cls, based on the signature of the given base_func but with a new name.
"""
# Get the function's signature
sig = signature(base_func)
new_sig = str(sig)[1 : -1] # omit the parentheses
args = comma_join(sig.parameters)
# Add extra args
if extra_args:
if args:
args = comma_join([args] + extra_args)
new_sig = comma_join([new_sig] + extra_args)
else:
args = comma_join(extra_args)
new_sig = comma_join(extra_args)
# Get default values for args
argdefs = tuple(p.default for p in sig.parameters.values() if p.default != Parameter.empty)
# Build the new function
new_code = compile('def {new_name}({new_sig}): return F("{new_name}", {args})'.format(**locals()),
__file__, 'exec')
new_func = FunctionType(code=new_code.co_consts[0], globals=globals(), name=new_name, argdefs=argdefs)
# If base_func was parametric, new_func should be too
if getattr(base_func, 'f_parametric', False):
new_func = parametric(new_func)
# Attach to class
setattr(cls, new_name, new_func)
class F(Cond, FunctionOperatorsMixin, metaclass=FMeta):
"""
Represents a database function call and its arguments.
It doubles as a query condition when the function returns a boolean result.
"""
def __init__(self, name, *args):
"""
Initializer.
"""
self.name = name
self.args = args
self.is_binary_operator = False
def __repr__(self):
return self.to_sql()
def to_sql(self, *args):
"""
Generates an SQL string for this function and its arguments.
For example if the function name is a symbol of a binary operator:
(2.54 * `height`)
For other functions:
gcd(12, 300)
"""
if self.is_binary_operator:
prefix = ''
sep = ' ' + self.name + ' '
else:
prefix = self.name
sep = ', '
arg_strs = (arg_to_sql(arg) for arg in self.args if arg != NO_VALUE)
return prefix + '(' + sep.join(arg_strs) + ')'
# Arithmetic functions
@staticmethod
@binary_operator
def plus(a, b):
return F('+', a, b)
@staticmethod
@binary_operator
def minus(a, b):
return F('-', a, b)
@staticmethod
@binary_operator
def multiply(a, b):
return F('*', a, b)
@staticmethod
@binary_operator
def divide(a, b):
return F('/', a, b)
@staticmethod
def intDiv(a, b):
return F('intDiv', a, b)
@staticmethod
def intDivOrZero(a, b):
return F('intDivOrZero', a, b)
@staticmethod
@binary_operator
def modulo(a, b):
return F('%', a, b)
@staticmethod
def negate(a):
return F('negate', a)
@staticmethod
def abs(a):
return F('abs', a)
@staticmethod
def gcd(a, b):
return F('gcd', a, b)
@staticmethod
def lcm(a, b):
return F('lcm', a, b)
# Comparison functions
@staticmethod
@binary_operator
def equals(a, b):
return F('=', a, b)
@staticmethod
@binary_operator
def notEquals(a, b):
return F('!=', a, b)
@staticmethod
@binary_operator
def less(a, b):
return F('<', a, b)
@staticmethod
@binary_operator
def greater(a, b):
return F('>', a, b)
@staticmethod
@binary_operator
def lessOrEquals(a, b):
return F('<=', a, b)
@staticmethod
@binary_operator
def greaterOrEquals(a, b):
return F('>=', a, b)
# Logical functions (should be used as python operators: & | ^ ~)
@staticmethod
@binary_operator
def _and(a, b):
return F('AND', a, b)
@staticmethod
@binary_operator
def _or(a, b):
return F('OR', a, b)
@staticmethod
def _xor(a, b):
return F('xor', a, b)
@staticmethod
def _not(a):
return F('not', a)
# in / not in
@staticmethod
@binary_operator
def _in(a, b):
if is_iterable(b) and not isinstance(b, (tuple, QuerySet)):
b = tuple(b)
return F('IN', a, b)
@staticmethod
@binary_operator
def _notIn(a, b):
if is_iterable(b) and not isinstance(b, (tuple, QuerySet)):
b = tuple(b)
return F('NOT IN', a, b)
# Functions for working with dates and times
@staticmethod
def toYear(d):
return F('toYear', d)
@staticmethod
def toISOYear(d, timezone=''):
return F('toISOYear', d, timezone)
@staticmethod
def toQuarter(d, timezone=''):
return F('toQuarter', d, timezone) if timezone else F('toQuarter', d)
@staticmethod
def toMonth(d):
return F('toMonth', d)
@staticmethod
def toWeek(d, mode=0, timezone=''):
return F('toWeek', d, mode, timezone)
@staticmethod
def toISOWeek(d, timezone=''):
return F('toISOWeek', d, timezone) if timezone else F('toISOWeek', d)
@staticmethod
def toDayOfYear(d):
return F('toDayOfYear', d)
@staticmethod
def toDayOfMonth(d):
return F('toDayOfMonth', d)
@staticmethod
def toDayOfWeek(d):
return F('toDayOfWeek', d)
@staticmethod
def toHour(d):
return F('toHour', d)
@staticmethod
def toMinute(d):
return F('toMinute', d)
@staticmethod
def toSecond(d):
return F('toSecond', d)
@staticmethod
def toMonday(d):
return F('toMonday', d)
@staticmethod
def toStartOfMonth(d):
return F('toStartOfMonth', d)
@staticmethod
def toStartOfQuarter(d):
return F('toStartOfQuarter', d)
@staticmethod
def toStartOfYear(d):
return F('toStartOfYear', d)
@staticmethod
def toStartOfISOYear(d):
return F('toStartOfISOYear', d)
@staticmethod
def toStartOfTenMinutes(d):
return F('toStartOfTenMinutes', d)
@staticmethod
def toStartOfWeek(d, mode=0):
return F('toStartOfWeek', d)
@staticmethod
def toStartOfMinute(d):
return F('toStartOfMinute', d)
@staticmethod
def toStartOfFiveMinute(d):
return F('toStartOfFiveMinute', d)
@staticmethod
def toStartOfFifteenMinutes(d):
return F('toStartOfFifteenMinutes', d)
@staticmethod
def toStartOfHour(d):
return F('toStartOfHour', d)
@staticmethod
def toStartOfDay(d):
return F('toStartOfDay', d)
@staticmethod
def toTime(d, timezone=''):
return F('toTime', d, timezone)
@staticmethod
def toTimeZone(dt, timezone):
return F('toTimeZone', dt, timezone)
@staticmethod
def toUnixTimestamp(dt, timezone=''):
return F('toUnixTimestamp', dt, timezone)
@staticmethod
def toYYYYMM(dt, timezone=''):
return F('toYYYYMM', dt, timezone) if timezone else F('toYYYYMM', dt)
@staticmethod
def toYYYYMMDD(dt, timezone=''):
return F('toYYYYMMDD', dt, timezone) if timezone else F('toYYYYMMDD', dt)
@staticmethod
def toYYYYMMDDhhmmss(dt, timezone=''):
return F('toYYYYMMDDhhmmss', dt, timezone) if timezone else F('toYYYYMMDDhhmmss', dt)
@staticmethod
def toRelativeYearNum(d, timezone=''):
return F('toRelativeYearNum', d, timezone)
@staticmethod
def toRelativeMonthNum(d, timezone=''):
return F('toRelativeMonthNum', d, timezone)
@staticmethod
def toRelativeWeekNum(d, timezone=''):
return F('toRelativeWeekNum', d, timezone)
@staticmethod
def toRelativeDayNum(d, timezone=''):
return F('toRelativeDayNum', d, timezone)
@staticmethod
def toRelativeHourNum(d, timezone=''):
return F('toRelativeHourNum', d, timezone)
@staticmethod
def toRelativeMinuteNum(d, timezone=''):
return F('toRelativeMinuteNum', d, timezone)
@staticmethod
def toRelativeSecondNum(d, timezone=''):
return F('toRelativeSecondNum', d, timezone)
@staticmethod
def now():
return F('now')
@staticmethod
def today():
return F('today')
@staticmethod
def yesterday():
return F('yesterday')
@staticmethod
def timeSlot(d):
return F('timeSlot', d)
@staticmethod
def timeSlots(start_time, duration):
return F('timeSlots', start_time, F.toUInt32(duration))
@staticmethod
def formatDateTime(d, format, timezone=''):
return F('formatDateTime', d, format, timezone)
@staticmethod
def addDays(d, n, timezone=NO_VALUE):
return F('addDays', d, n, timezone)
@staticmethod
def addHours(d, n, timezone=NO_VALUE):
return F('addHours', d, n, timezone)
@staticmethod
def addMinutes(d, n, timezone=NO_VALUE):
return F('addMinutes', d, n, timezone)
@staticmethod
def addMonths(d, n, timezone=NO_VALUE):
return F('addMonths', d, n, timezone)
@staticmethod
def addQuarters(d, n, timezone=NO_VALUE):
return F('addQuarters', d, n, timezone)
@staticmethod
def addSeconds(d, n, timezone=NO_VALUE):
return F('addSeconds', d, n, timezone)
@staticmethod
def addWeeks(d, n, timezone=NO_VALUE):
return F('addWeeks', d, n, timezone)
@staticmethod
def addYears(d, n, timezone=NO_VALUE):
return F('addYears', d, n, timezone)
@staticmethod
def subtractDays(d, n, timezone=NO_VALUE):
return F('subtractDays', d, n, timezone)
@staticmethod
def subtractHours(d, n, timezone=NO_VALUE):
return F('subtractHours', d, n, timezone)
@staticmethod
def subtractMinutes(d, n, timezone=NO_VALUE):
return F('subtractMinutes', d, n, timezone)
@staticmethod
def subtractMonths(d, n, timezone=NO_VALUE):
return F('subtractMonths', d, n, timezone)
@staticmethod
def subtractQuarters(d, n, timezone=NO_VALUE):
return F('subtractQuarters', d, n, timezone)
@staticmethod
def subtractSeconds(d, n, timezone=NO_VALUE):
return F('subtractSeconds', d, n, timezone)
@staticmethod
def subtractWeeks(d, n, timezone=NO_VALUE):
return F('subtractWeeks', d, n, timezone)
@staticmethod
def subtractYears(d, n, timezone=NO_VALUE):
return F('subtractYears', d, n, timezone)
@staticmethod
def toIntervalSecond(number):
return F('toIntervalSecond', number)
@staticmethod
def toIntervalMinute(number):
return F('toIntervalMinute', number)
@staticmethod
def toIntervalHour(number):
return F('toIntervalHour', number)
@staticmethod
def toIntervalDay(number):
return F('toIntervalDay', number)
@staticmethod
def toIntervalWeek(number):
return F('toIntervalWeek', number)
@staticmethod
def toIntervalMonth(number):
return F('toIntervalMonth', number)
@staticmethod
def toIntervalQuarter(number):
return F('toIntervalQuarter', number)
@staticmethod
def toIntervalYear(number):
return F('toIntervalYear', number)
# Type conversion functions
@staticmethod
@type_conversion
def toUInt8(x):
return F('toUInt8', x)
@staticmethod
@type_conversion
def toUInt16(x):
return F('toUInt16', x)
@staticmethod
@type_conversion
def toUInt32(x):
return F('toUInt32', x)
@staticmethod
@type_conversion
def toUInt64(x):
return F('toUInt64', x)
@staticmethod
@type_conversion
def toInt8(x):
return F('toInt8', x)
@staticmethod
@type_conversion
def toInt16(x):
return F('toInt16', x)
@staticmethod
@type_conversion
def toInt32(x):
return F('toInt32', x)
@staticmethod
@type_conversion
def toInt64(x):
return F('toInt64', x)
@staticmethod
@type_conversion
def toFloat32(x):
return F('toFloat32', x)
@staticmethod
@type_conversion
def toFloat64(x):
return F('toFloat64', x)
@staticmethod
@type_conversion
def toDecimal32(x, scale):
return F('toDecimal32', x, scale)
@staticmethod
@type_conversion
def toDecimal64(x, scale):
return F('toDecimal64', x, scale)
@staticmethod
@type_conversion
def toDecimal128(x, scale):
return F('toDecimal128', x, scale)
@staticmethod
@type_conversion
def toDate(x):
return F('toDate', x)
@staticmethod
@type_conversion
def toDateTime(x):
return F('toDateTime', x)
@staticmethod
@type_conversion
def toDateTime64(x, precision, timezone=NO_VALUE):
return F('toDateTime64', x, precision, timezone)
@staticmethod
def toString(x):
return F('toString', x)
@staticmethod
def toFixedString(s, length):
return F('toFixedString', s, length)
@staticmethod
def toStringCutToZero(s):
return F('toStringCutToZero', s)
@staticmethod
def CAST(x, type):
return F('CAST', x, type)
@staticmethod
@type_conversion
def parseDateTimeBestEffort(d, timezone=NO_VALUE):
return F('parseDateTimeBestEffort', d, timezone)
# Functions for working with strings
@staticmethod
def empty(s):
return F('empty', s)
@staticmethod
def notEmpty(s):
return F('notEmpty', s)
@staticmethod
@with_utf8_support
def length(s):
return F('length', s)
@staticmethod
@with_utf8_support
def lower(s):
return F('lower', s)
@staticmethod
@with_utf8_support
def upper(s):
return F('upper', s)
@staticmethod
@with_utf8_support
def reverse(s):
return F('reverse', s)
@staticmethod
def concat(*args):
return F('concat', *args)
@staticmethod
@with_utf8_support
def substring(s, offset, length):
return F('substring', s, offset, length)
@staticmethod
def appendTrailingCharIfAbsent(s, c):
return F('appendTrailingCharIfAbsent', s, c)
@staticmethod
def convertCharset(s, from_charset, to_charset):
return F('convertCharset', s, from_charset, to_charset)
@staticmethod
def base64Encode(s):
return F('base64Encode', s)
@staticmethod
def base64Decode(s):
return F('base64Decode', s)
@staticmethod
def tryBase64Decode(s):
return F('tryBase64Decode', s)
@staticmethod
def endsWith(s, suffix):
return F('endsWith', s, suffix)
@staticmethod
def startsWith(s, prefix):
return F('startsWith', s, prefix)
@staticmethod
def trimLeft(s):
return F('trimLeft', s)
@staticmethod
def trimRight(s):
return F('trimRight', s)
@staticmethod
def trimBoth(s):
return F('trimBoth', s)
@staticmethod
def CRC32(s):
return F('CRC32', s)
# Functions for searching in strings
@staticmethod
@with_utf8_support
def position(haystack, needle):
return F('position', haystack, needle)
@staticmethod
@with_utf8_support
def positionCaseInsensitive(haystack, needle):
return F('positionCaseInsensitive', haystack, needle)
@staticmethod
def like(haystack, pattern):
return F('like', haystack, pattern)
@staticmethod
def notLike(haystack, pattern):
return F('notLike', haystack, pattern)
@staticmethod
def match(haystack, pattern):
return F('match', haystack, pattern)
@staticmethod
def extract(haystack, pattern):
return F('extract', haystack, pattern)
@staticmethod
def extractAll(haystack, pattern):
return F('extractAll', haystack, pattern)
@staticmethod
@with_utf8_support
def ngramDistance(haystack, needle):
return F('ngramDistance', haystack, needle)
@staticmethod
@with_utf8_support
def ngramDistanceCaseInsensitive(haystack, needle):
return F('ngramDistanceCaseInsensitive', haystack, needle)
@staticmethod
@with_utf8_support
def ngramSearch(haystack, needle):
return F('ngramSearch', haystack, needle)
@staticmethod
@with_utf8_support
def ngramSearchCaseInsensitive(haystack, needle):
return F('ngramSearchCaseInsensitive', haystack, needle)
# Functions for replacing in strings
@staticmethod
def replace(haystack, pattern, replacement):
return F('replace', haystack, pattern, replacement)
replaceAll = replace
@staticmethod
def replaceAll(haystack, pattern, replacement):
return F('replaceAll', haystack, pattern, replacement)
@staticmethod
def replaceOne(haystack, pattern, replacement):
return F('replaceOne', haystack, pattern, replacement)
@staticmethod
def replaceRegexpAll(haystack, pattern, replacement):
return F('replaceRegexpAll', haystack, pattern, replacement)
@staticmethod
def replaceRegexpOne(haystack, pattern, replacement):
return F('replaceRegexpOne', haystack, pattern, replacement)
@staticmethod
def regexpQuoteMeta(x):
return F('regexpQuoteMeta', x)
# Mathematical functions
@staticmethod
def e():
return F('e')
@staticmethod
def pi():
return F('pi')
@staticmethod
def exp(x):
return F('exp', x)
@staticmethod
def log(x):
return F('log', x)
ln = log
@staticmethod
def exp2(x):
return F('exp2', x)
@staticmethod
def log2(x):
return F('log2', x)
@staticmethod
def exp10(x):
return F('exp10', x)
@staticmethod
def log10(x):
return F('log10', x)
@staticmethod
def sqrt(x):
return F('sqrt', x)
@staticmethod
def cbrt(x):
return F('cbrt', x)
@staticmethod
def erf(x):
return F('erf', x)
@staticmethod
def erfc(x):
return F('erfc', x)
@staticmethod
def lgamma(x):
return F('lgamma', x)
@staticmethod
def tgamma(x):
return F('tgamma', x)
@staticmethod
def sin(x):
return F('sin', x)
@staticmethod
def cos(x):
return F('cos', x)
@staticmethod
def tan(x):
return F('tan', x)
@staticmethod
def asin(x):
return F('asin', x)
@staticmethod
def acos(x):
return F('acos', x)
@staticmethod
def atan(x):
return F('atan', x)
@staticmethod
def power(x, y):
return F('power', x, y)
pow = power
@staticmethod
def intExp10(x):
return F('intExp10', x)
@staticmethod
def intExp2(x):
return F('intExp2', x)
# Rounding functions
@staticmethod
def floor(x, n=None):
return F('floor', x, n) if n else F('floor', x)
@staticmethod
def ceiling(x, n=None):
return F('ceiling', x, n) if n else F('ceiling', x)
ceil = ceiling
@staticmethod
def round(x, n=None):
return F('round', x, n) if n else F('round', x)
@staticmethod
def roundAge(x):
return F('roundAge', x)
@staticmethod
def roundDown(x, y):
return F('roundDown', x, y)
@staticmethod
def roundDuration(x):
return F('roundDuration', x)
@staticmethod
def roundToExp2(x):
return F('roundToExp2', x)
# Functions for working with arrays
@staticmethod
def emptyArrayDate():
return F('emptyArrayDate')
@staticmethod
def emptyArrayDateTime():
return F('emptyArrayDateTime')
@staticmethod
def emptyArrayFloat32():
return F('emptyArrayFloat32')
@staticmethod
def emptyArrayFloat64():
return F('emptyArrayFloat64')
@staticmethod
def emptyArrayInt16():
return F('emptyArrayInt16')
@staticmethod
def emptyArrayInt32():
return F('emptyArrayInt32')
@staticmethod
def emptyArrayInt64():
return F('emptyArrayInt64')
@staticmethod
def emptyArrayInt8():
return F('emptyArrayInt8')
@staticmethod
def emptyArrayString():
return F('emptyArrayString')
@staticmethod
def emptyArrayUInt16():
return F('emptyArrayUInt16')
@staticmethod
def emptyArrayUInt32():
return F('emptyArrayUInt32')
@staticmethod
def emptyArrayUInt64():
return F('emptyArrayUInt64')
@staticmethod
def emptyArrayUInt8():
return F('emptyArrayUInt8')
@staticmethod
def emptyArrayToSingle(x):
return F('emptyArrayToSingle', x)
@staticmethod
def range(n):
return F('range', n)
@staticmethod
def array(*args):
return F('array', *args)
@staticmethod
def arrayConcat(*args):
return F('arrayConcat', *args)
@staticmethod
def arrayElement(arr, n):
return F('arrayElement', arr, n)
@staticmethod
def has(arr, x):
return F('has', arr, x)
@staticmethod
def hasAll(arr, x):
return F('hasAll', arr, x)
@staticmethod
def hasAny(arr, x):
return F('hasAny', arr, x)
@staticmethod
def indexOf(arr, x):
return F('indexOf', arr, x)
@staticmethod
def countEqual(arr, x):
return F('countEqual', arr, x)
@staticmethod
def arrayEnumerate(arr):
return F('arrayEnumerate', arr)
@staticmethod
def arrayEnumerateDense(*args):
return F('arrayEnumerateDense', *args)
@staticmethod
def arrayEnumerateDenseRanked(*args):
return F('arrayEnumerateDenseRanked', *args)
@staticmethod
def arrayEnumerateUniq(*args):
return F('arrayEnumerateUniq', *args)
@staticmethod
def arrayEnumerateUniqRanked(*args):
return F('arrayEnumerateUniqRanked', *args)
@staticmethod
def arrayPopBack(arr):
return F('arrayPopBack', arr)
@staticmethod
def arrayPopFront(arr):
return F('arrayPopFront', arr)
@staticmethod
def arrayPushBack(arr, x):
return F('arrayPushBack', arr, x)
@staticmethod
def arrayPushFront(arr, x):
return F('arrayPushFront', arr, x)
@staticmethod
def arrayResize(array, size, extender=None):
return F('arrayResize', array, size, extender) if extender is not None else F('arrayResize', array, size)
@staticmethod
def arraySlice(array, offset, length=None):
return F('arraySlice', array, offset, length) if length is not None else F('arraySlice', array, offset)
@staticmethod
def arrayUniq(*args):
return F('arrayUniq', *args)
@staticmethod
def arrayJoin(arr):
return F('arrayJoin', arr)
@staticmethod
def arrayDifference(arr):
return F('arrayDifference', arr)
@staticmethod
def arrayDistinct(x):
return F('arrayDistinct', x)
@staticmethod
def arrayIntersect(*args):
return F('arrayIntersect', *args)
@staticmethod
def arrayReduce(agg_func_name, *args):
return F('arrayReduce', agg_func_name, *args)
@staticmethod
def arrayReverse(arr):
return F('arrayReverse', arr)
# Functions for splitting and merging strings and arrays
@staticmethod
def splitByChar(sep, s):
return F('splitByChar', sep, s)
@staticmethod
def splitByString(sep, s):
return F('splitByString', sep, s)
@staticmethod
def arrayStringConcat(arr, sep=None):
return F('arrayStringConcat', arr, sep) if sep else F('arrayStringConcat', arr)
@staticmethod
def alphaTokens(s):
return F('alphaTokens', s)
# Bit functions
@staticmethod
def bitAnd(x, y):
return F('bitAnd', x, y)
@staticmethod
def bitNot(x):
return F('bitNot', x)
@staticmethod
def bitOr(x, y):
return F('bitOr', x, y)
@staticmethod
def bitRotateLeft(x, y):
return F('bitRotateLeft', x, y)
@staticmethod
def bitRotateRight(x, y):
return F('bitRotateRight', x, y)
@staticmethod
def bitShiftLeft(x, y):
return F('bitShiftLeft', x, y)
@staticmethod
def bitShiftRight(x, y):
return F('bitShiftRight', x, y)
@staticmethod
def bitTest(x, y):
return F('bitTest', x, y)
@staticmethod
def bitTestAll(x, *args):
return F('bitTestAll', x, *args)
@staticmethod
def bitTestAny(x, *args):
return F('bitTestAny', x, *args)
@staticmethod
def bitXor(x, y):
return F('bitXor', x, y)
# Bitmap functions
@staticmethod
def bitmapAnd(x, y):
return F('bitmapAnd', x, y)
@staticmethod
def bitmapAndCardinality(x, y):
return F('bitmapAndCardinality', x, y)
@staticmethod
def bitmapAndnot(x, y):
return F('bitmapAndnot', x, y)
@staticmethod
def bitmapAndnotCardinality(x, y):
return F('bitmapAndnotCardinality', x, y)
@staticmethod
def bitmapBuild(x):
return F('bitmapBuild', x)
@staticmethod
def bitmapCardinality(x):
return F('bitmapCardinality', x)
@staticmethod
def bitmapContains(haystack, needle):
return F('bitmapContains', haystack, needle)
@staticmethod
def bitmapHasAll(x, y):
return F('bitmapHasAll', x, y)
@staticmethod
def bitmapHasAny(x, y):
return F('bitmapHasAny', x, y)
@staticmethod
def bitmapOr(x, y):
return F('bitmapOr', x, y)
@staticmethod
def bitmapOrCardinality(x, y):
return F('bitmapOrCardinality', x, y)
@staticmethod
def bitmapToArray(x):
return F('bitmapToArray', x)
@staticmethod
def bitmapXor(x, y):
return F('bitmapXor', x, y)
@staticmethod
def bitmapXorCardinality(x, y):
return F('bitmapXorCardinality', x, y)
# Hash functions
@staticmethod
def halfMD5(*args):
return F('halfMD5', *args)
@staticmethod
def MD5(s):
return F('MD5', s)
@staticmethod
def sipHash128(*args):
return F('sipHash128', *args)
@staticmethod
def sipHash64(*args):
return F('sipHash64', *args)
@staticmethod
def cityHash64(*args):
return F('cityHash64', *args)
@staticmethod
def intHash32(x):
return F('intHash32', x)
@staticmethod
def intHash64(x):
return F('intHash64', x)
@staticmethod
def SHA1(s):
return F('SHA1', s)
@staticmethod
def SHA224(s):
return F('SHA224', s)
@staticmethod
def SHA256(s):
return F('SHA256', s)
@staticmethod
def URLHash(url, n=None):
return F('URLHash', url, n) if n is not None else F('URLHash', url)
@staticmethod
def farmHash64(*args):
return F('farmHash64',*args)
@staticmethod
def javaHash(s):
return F('javaHash', s)
@staticmethod
def hiveHash(s):
return F('hiveHash', s)
@staticmethod
def metroHash64(*args):
return F('metroHash64', *args)
@staticmethod
def jumpConsistentHash(x, buckets):
return F('jumpConsistentHash', x, buckets)
@staticmethod
def murmurHash2_32(*args):
return F('murmurHash2_32', *args)
@staticmethod
def murmurHash2_64(*args):
return F('murmurHash2_64', *args)
@staticmethod
def murmurHash3_32(*args):
return F('murmurHash3_32', *args)
@staticmethod
def murmurHash3_64(*args):
return F('murmurHash3_64', *args)
@staticmethod
def murmurHash3_128(s):
return F('murmurHash3_128', s)
@staticmethod
def xxHash32(*args):
return F('xxHash32', *args)
@staticmethod
def xxHash64(*args):
return F('xxHash64', *args)
# Functions for generating pseudo-random numbers
@staticmethod
def rand(dummy=None):
return F('rand') if dummy is None else F('rand', dummy)
@staticmethod
def rand64(dummy=None):
return F('rand64') if dummy is None else F('rand64', dummy)
@staticmethod
def randConstant(dummy=None):
return F('randConstant') if dummy is None else F('randConstant', dummy)
# Encoding functions
@staticmethod
def hex(x):
return F('hex', x)
@staticmethod
def unhex(x):
return F('unhex', x)
@staticmethod
def bitmaskToArray(x):
return F('bitmaskToArray', x)
@staticmethod
def bitmaskToList(x):
return F('bitmaskToList', x)
# Functions for working with UUID
@staticmethod
def generateUUIDv4():
return F('generateUUIDv4')
@staticmethod
def toUUID(s):
return F('toUUID', s)
@staticmethod
def UUIDNumToString(s):
return F('UUIDNumToString', s)
@staticmethod
def UUIDStringToNum(s):
return F('UUIDStringToNum', s)
# Functions for working with IP addresses
@staticmethod
def IPv4CIDRToRange(ipv4, cidr):
return F('IPv4CIDRToRange', ipv4, cidr)
@staticmethod
def IPv4NumToString(num):
return F('IPv4NumToString', num)
@staticmethod
def IPv4NumToStringClassC(num):
return F('IPv4NumToStringClassC', num)
@staticmethod
def IPv4StringToNum(s):
return F('IPv4StringToNum', s)
@staticmethod
def IPv4ToIPv6(ipv4):
return F('IPv4ToIPv6', ipv4)
@staticmethod
def IPv6CIDRToRange(ipv6, cidr):
return F('IPv6CIDRToRange', ipv6, cidr)
@staticmethod
def IPv6NumToString(num):
return F('IPv6NumToString', num)
@staticmethod
def IPv6StringToNum(s):
return F('IPv6StringToNum', s)
@staticmethod
def toIPv4(ipv4):
return F('toIPv4', ipv4)
@staticmethod
def toIPv6(ipv6):
return F('toIPv6', ipv6)
# Aggregate functions
@staticmethod
@aggregate
def any(x):
return F('any', x)
@staticmethod
@aggregate
def anyHeavy(x):
return F('anyHeavy', x)
@staticmethod
@aggregate
def anyLast(x):
return F('anyLast', x)
@staticmethod
@aggregate
def argMax(x, y):
return F('argMax', x, y)
@staticmethod
@aggregate
def argMin(x, y):
return F('argMin', x, y)
@staticmethod
@aggregate
def avg(x):
return F('avg', x)
@staticmethod
@aggregate
def corr(x, y):
return F('corr', x, y)
@staticmethod
@aggregate
def count():
return F('count')
@staticmethod
@aggregate
def covarPop(x, y):
return F('covarPop', x, y)
@staticmethod
@aggregate
def covarSamp(x, y):
return F('covarSamp', x, y)
@staticmethod
@aggregate
def kurtPop(x):
return F('kurtPop', x)
@staticmethod
@aggregate
def kurtSamp(x):
return F('kurtSamp', x)
@staticmethod
@aggregate
def min(x):
return F('min', x)
@staticmethod
@aggregate
def max(x):
return F('max', x)
@staticmethod
@aggregate
def skewPop(x):
return F('skewPop', x)
@staticmethod
@aggregate
def skewSamp(x):
return F('skewSamp', x)
@staticmethod
@aggregate
def sum(x):
return F('sum', x)
@staticmethod
@aggregate
def uniq(*args):
return F('uniq', *args)
@staticmethod
@aggregate
def uniqExact(*args):
return F('uniqExact', *args)
@staticmethod
@aggregate
def uniqHLL12(*args):
return F('uniqHLL12', *args)
@staticmethod
@aggregate
def varPop(x):
return F('varPop', x)
@staticmethod
@aggregate
def varSamp(x):
return F('varSamp', x)
@staticmethod
@aggregate
@parametric
def quantile(expr):
return F('quantile', expr)
@staticmethod
@aggregate
@parametric
def quantileDeterministic(expr, determinator):
return F('quantileDeterministic', expr, determinator)
@staticmethod
@aggregate
@parametric
def quantileExact(expr):
return F('quantileExact', expr)
@staticmethod
@aggregate
@parametric
def quantileExactWeighted(expr, weight):
return F('quantileExactWeighted', expr, weight)
@staticmethod
@aggregate
@parametric
def quantileTiming(expr):
return F('quantileTiming', expr)
@staticmethod
@aggregate
@parametric
def quantileTimingWeighted(expr, weight):
return F('quantileTimingWeighted', expr, weight)
@staticmethod
@aggregate
@parametric
def quantileTDigest(expr):
return F('quantileTDigest', expr)
@staticmethod
@aggregate
@parametric
def quantileTDigestWeighted(expr, weight):
return F('quantileTDigestWeighted', expr, weight)
@staticmethod
@aggregate
@parametric
def quantiles(expr):
return F('quantiles', expr)
@staticmethod
@aggregate
@parametric
def quantilesDeterministic(expr, determinator):
return F('quantilesDeterministic', expr, determinator)
@staticmethod
@aggregate
@parametric
def quantilesExact(expr):
return F('quantilesExact', expr)
@staticmethod
@aggregate
@parametric
def quantilesExactWeighted(expr, weight):
return F('quantilesExactWeighted', expr, weight)
@staticmethod
@aggregate
@parametric
def quantilesTiming(expr):
return F('quantilesTiming', expr)
@staticmethod
@aggregate
@parametric
def quantilesTimingWeighted(expr, weight):
return F('quantilesTimingWeighted', expr, weight)
@staticmethod
@aggregate
@parametric
def quantilesTDigest(expr):
return F('quantilesTDigest', expr)
@staticmethod
@aggregate
@parametric
def quantilesTDigestWeighted(expr, weight):
return F('quantilesTDigestWeighted', expr, weight)
@staticmethod
@aggregate
@parametric
def topK(expr):
return F('topK', expr)
@staticmethod
@aggregate
@parametric
def topKWeighted(expr, weight):
return F('topKWeighted', expr, weight)
# Null handling functions
@staticmethod
def ifNull(x, y):
return F('ifNull', x, y)
@staticmethod
def nullIf(x, y):
return F('nullIf', x, y)
@staticmethod
def isNotNull(x):
return F('isNotNull', x)
@staticmethod
def isNull(x):
return F('isNull', x)
@staticmethod
def coalesce(*args):
return F('coalesce', *args)
# Misc functions
@staticmethod
def ifNotFinite(x, y):
return F('ifNotFinite', x, y)
@staticmethod
def isFinite(x):
return F('isFinite', x)
@staticmethod
def isInfinite(x):
return F('isInfinite', x)
@staticmethod
def isNaN(x):
return F('isNaN', x)
@staticmethod
def least(x, y):
return F('least', x, y)
@staticmethod
def greatest(x, y):
return F('greatest', x, y)
# Dictionary functions
@staticmethod
def dictGet(dict_name, attr_name, id_expr):
return F('dictGet', dict_name, attr_name, id_expr)
@staticmethod
def dictGetOrDefault(dict_name, attr_name, id_expr, default):
return F('dictGetOrDefault', dict_name, attr_name, id_expr, default)
@staticmethod
def dictHas(dict_name, id_expr):
return F('dictHas', dict_name, id_expr)
@staticmethod
def dictGetHierarchy(dict_name, id_expr):
return F('dictGetHierarchy', dict_name, id_expr)
@staticmethod
def dictIsIn(dict_name, child_id_expr, ancestor_id_expr):
return F('dictIsIn', dict_name, child_id_expr, ancestor_id_expr)
# Expose only relevant classes in import *
__all__ = ['F']
| {
"repo_name": "Infinidat/infi.clickhouse_orm",
"path": "src/infi/clickhouse_orm/funcs.py",
"copies": "1",
"size": "41249",
"license": "bsd-3-clause",
"hash": 247532796889790850,
"line_mean": 21.701706109,
"line_max": 113,
"alpha_frac": 0.59843875,
"autogenerated": false,
"ratio": 3.785701174743025,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48841399247430245,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from inspect import signature, Parameter
from typing import Tuple, List, Dict, Type
class TypeHintError(TypeError):
pass
class ArgumentTypeHintError(TypeHintError):
def __init__(
self, argument_name, func_name, expected_type, given_type
) -> None:
super().__init__(
'Argument %s passed to %s must be an instance of %s, %s given' % (
argument_name, func_name, expected_type, given_type
)
)
class ReturnValueTypeHintError(TypeHintError):
def __init__(
self, func_name, expected_type, given_type
) -> None:
super().__init__(
"Value returned by %s must be an instance of %s, %s returned" % (
func_name, expected_type, given_type
)
)
class StrictHint(object):
__func = None
__sig = None
def __call__(self, func):
self.__func = func
self.__sig = signature(func)
@wraps(self.__func)
def wrapper(*args, **kwargs):
self.__assert_args(args)
self.__assert_kwargs(kwargs)
result = self.__func(*args, **kwargs)
self.__assert_return(result)
return result
return wrapper
def __assert_args(self, args: tuple) -> None:
argvals = dict(zip(self.__sig.parameters.keys(), args))
if not argvals:
return
for param in argvals.keys():
self.__assert_param(param, self.__sig.parameters[param], argvals)
def __assert_kwargs(self, kwargs: dict) -> None:
if not kwargs:
return
for param in kwargs.keys():
self.__assert_param(param, self.__sig.parameters[param], kwargs)
def __assert_param(
self, name: str, param: Parameter, values: dict
) -> None:
if param.annotation == param.empty:
return
val = values[name]
if not self.__matches_hint(val, param.annotation, param.default):
raise ArgumentTypeHintError(
name,
self.__func_name(self.__func),
param.annotation,
type(values[name])
)
def __assert_return(self, result: Parameter) -> None:
if self.__sig.return_annotation == self.__sig.empty:
return
if not self.__matches_hint(result, self.__sig.return_annotation):
raise ReturnValueTypeHintError(
self.__func_name(self.__func),
self.__sig.return_annotation,
type(result)
)
def __matches_hint(self, value, expected, default=None) -> bool:
if type(expected) == list:
expected = list
try:
if expected.__module__ == 'typing':
expected = self.__simplify_typing(expected)
except AttributeError:
pass
return value == default or isinstance(value, expected)
def __simplify_typing(self, expected) -> Type:
if not hasattr(expected, '__name__'):
return expected.__args__
mapping = {
Tuple.__name__: tuple,
List.__name__: list,
Dict.__name__: dict,
}
if expected.__name__ in mapping:
return mapping[expected.__name__]
if hasattr(expected, '__supertype__'):
return expected.__supertype__
def __func_name(self, func) -> str:
return func.__qualname__.split('.<locals>.', 1)[-1]
| {
"repo_name": "potfur/strict-hint",
"path": "strict_hint/strict_hint.py",
"copies": "1",
"size": "3512",
"license": "mit",
"hash": 1325314122853437400,
"line_mean": 28.2666666667,
"line_max": 78,
"alpha_frac": 0.5390091116,
"autogenerated": false,
"ratio": 4.335802469135802,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5374811580735802,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from .inspector import Gadget
from .exceptions import PyCondition, PyConditionError
from .stage import Stage
class Pre(object):
def __init__(self):
self.funcTable = {}
class PreCondition(object):
context = Pre()
def __init__(self, name):
self.name = name
def _map(self, func):
try:
func = func._original_func
func.__doc__ = func._original_func.__doc__
except:
pass
gadget = Gadget(func)
m = gadget.gogoMap()
params = [v[1] for v in sorted(
[(i, vv) for vv, i in m.items()], key=lambda a: a[0])]
name = (func.__module__, func.__name__, "( %s )" % ",".join(params))
self.funcName = "%s.%s%s" % name
if(name in self.context.funcTable):
self.argMap = PreCondition.context.funcTable[name]
else:
gadget = Gadget(func)
self.argMap = gadget.gogoMap()
PreCondition.context.funcTable[name] = self.argMap
def assertCondition(self, *args, **kwargs):
pass
def __call__(self, func):
wrapper = func
stage = Stage()
if(not func.__doc__ and stage.name == "Dev"):
doc = ""
func.__doc__ = ""
func.__doc__ += " %s - %s\n" % (self.name, self.__class__.__name__)
self._map(func)
@wraps(func)
def wrapper(*args, **kwargs):
if(stage.name == "Dev"):
self.assertCondition(*args, **kwargs)
return func(*args, **kwargs)
wrapper._original_func = func
return wrapper
class NotNone(PreCondition):
def __init__(self, name):
super(NotNone, self).__init__(name)
self.name = name
def assertCondition(self, *args, **kwargs):
if(args[self.argMap[self.name]] is None):
raise PyCondition(
"%s is None in function %s" %
(self.name, self.funcName))
class Between(PreCondition):
def __init__(self, name, lower, upper):
super(Between, self).__init__(name)
self.lower = lower
self.upper = upper
def assertCondition(self, *args, **kwargs):
v = args[self.argMap[self.name]]
if(not (self.lower <= v <= self.upper)):
raise PyCondition(
"%s <= %s <= %s did not hold for parameter %s in function %s" %
(self.lower, v, self.upper, self.name, self.funcName))
class GreaterThan(PreCondition):
def __init__(self, name, lower):
super(GreaterThan, self).__init__(name)
self.lower = lower
def assertCondition(self, *args, **kwargs):
v = args[self.argMap[self.name]]
if(not (self.lower < v)):
raise PyCondition(
"%s > %s did not hold for parameter %s in function %s" %
(v, self.lower, self.name, self.funcName))
class LessThan(PreCondition):
def __init__(self, name, upper):
super(LessThan, self).__init__(name)
self.upper = upper
def assertCondition(self, *args, **kwargs):
v = args[self.argMap[self.name]]
if(not (self.upper > v)):
raise PyCondition(
"%s < %s did not hold for parameter %s in function %s" %
(v, self.upper, self.name, self.funcName))
class Custom(PreCondition):
def __init__(self, name, check):
super(Custom, self).__init__(name)
self.check = check
def assertCondition(self, *args, **kwargs):
v = args[self.argMap[self.name]]
if(not self.check(v)):
raise PyCondition(
"%s did not hold for the parameter %s in the custom condition in function %s" %
(v, self.name, self.funcName))
class Instance(PreCondition):
def __init__(self, name, klass):
super(Instance, self).__init__(name)
self.klass = klass
def assertCondition(self, *args, **kwargs):
v = args[self.argMap[self.name]]
if(not isinstance(v, self.klass)):
raise PyCondition(
"%s is not a %s for parameter %s in function %s" %
(v, self.klass, self.name, self.funcName))
| {
"repo_name": "streed/pyConditions",
"path": "pyconditions/pre.py",
"copies": "1",
"size": "4219",
"license": "apache-2.0",
"hash": -5616237128750372000,
"line_mean": 26.2193548387,
"line_max": 96,
"alpha_frac": 0.54041242,
"autogenerated": false,
"ratio": 3.7336283185840706,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47740407385840705,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from io import StringIO
import sys
from flask import request, render_template
def templated(template=None):
""" Try to render a template for the decorated view
Template can be computed from the view name
If the view return something else than None or a dict, it will
be passed as is to flask
"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
# Run the view
ctx = f(*args, **kwargs)
# Create a context if needed
if ctx is None:
ctx = {}
# Or return exotic value. A redirect for example
elif not isinstance(ctx, dict):
return ctx
# Compute the template name if needed
template_name = template
if template_name is None:
template_name = request.endpoint.replace('.', '/') + '.html'
# Render
return render_template(template_name, **ctx)
return decorated_function
return decorator
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines())
sys.stdout = self._stdout
| {
"repo_name": "gkrnours/plume",
"path": "src/plume/utils.py",
"copies": "1",
"size": "1351",
"license": "mit",
"hash": 1568302598820296200,
"line_mean": 31.1666666667,
"line_max": 76,
"alpha_frac": 0.5810510733,
"autogenerated": false,
"ratio": 4.690972222222222,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001828847481021394,
"num_lines": 42
} |
from functools import wraps
from iso8601 import parse_date
from munch import munchify
from restkit import BasicAuth, errors, request, Resource
from retrying import retry
from simplejson import dumps, loads
from urlparse import parse_qs, urlparse
import logging
logger = logging.getLogger(__name__)
IGNORE_PARAMS = ('uri', 'path')
def verify_file(fn):
@wraps(fn)
def wrapper(self, file_, *args, **kwargs):
if isinstance(file_, str):
file_ = open(file_, 'rb')
if hasattr(file_, 'read'):
# A file-like object must have 'read' method
return fn(self, file_, *args, **kwargs)
else:
raise TypeError('Expected either a string '
'containing a path to file or a '
'file-like object, got {}'.format(type(file_)))
return wrapper
class InvalidResponse(Exception):
pass
class NoToken(Exception):
pass
class Client(Resource):
"""docstring for API"""
def __init__(self, key,
host_url="https://api-sandbox.openprocurement.org",
api_version='0.8',
resource='tenders',
params=None,
**kwargs):
super(Client, self).__init__(
host_url,
filters=[BasicAuth(key, "")],
**kwargs
)
self.prefix_path = '/api/{}/{}'.format(api_version, resource)
if not isinstance(params, dict):
params = {"mode": "_all_"}
self.params = params
self.headers = {"Content-Type": "application/json"}
# To perform some operations (e.g. create a tender)
# we first need to obtain a cookie. For that reason,
# here we send a HEAD request to a neutral URL.
self.head('/api/{}/spore'.format(api_version))
def request(self, method, path=None, payload=None, headers=None,
params_dict=None, **params):
_headers = dict(self.headers)
_headers.update(headers or {})
try:
response = super(Client, self).request(
method, path=path, payload=payload, headers=_headers,
params_dict=params_dict, **params
)
if 'Set-Cookie' in response.headers:
self.headers['Cookie'] = response.headers['Set-Cookie']
return response
except errors.ResourceNotFound as e:
if 'Set-Cookie' in e.response.headers:
self.headers['Cookie'] = e.response.headers['Set-Cookie']
raise e
def patch(self, path=None, payload=None, headers=None,
params_dict=None, **params):
""" HTTP PATCH
- payload: string passed to the body of the request
- path: string additionnal path to the uri
- headers: dict, optionnal headers that will
be added to HTTP request.
- params: Optionnal parameterss added to the request
"""
return self.request("PATCH", path=path, payload=payload,
headers=headers, params_dict=params_dict, **params)
def delete(self, path=None, headers=None):
""" HTTP DELETE
- path: string additionnal path to the uri
- headers: dict, optionnal headers that will
be added to HTTP request.
- params: Optionnal parameterss added to the request
"""
return self.request("DELETE", path=path, headers=headers)
def _update_params(self, params):
for key in params:
if key not in IGNORE_PARAMS:
self.params[key] = params[key]
###########################################################################
# GET ITEMS LIST API METHODS
###########################################################################
@retry(stop_max_attempt_number=5)
def get_tenders(self, params={}, feed='changes'):
params['feed'] = feed
try:
self._update_params(params)
response = self.get(
self.prefix_path,
params_dict=self.params)
if response.status_int == 200:
tender_list = munchify(loads(response.body_string()))
self._update_params(tender_list.next_page)
return tender_list.data
except errors.ResourceNotFound:
del self.params['offset']
raise
raise InvalidResponse
def get_latest_tenders(self, date, tender_id):
iso_dt = parse_date(date)
dt = iso_dt.strftime("%Y-%m-%d")
tm = iso_dt.strftime("%H:%M:%S")
response = self._get_resource_item(
'{}?offset={}T{}&opt_fields=tender_id&mode=test'.format(
self.prefix_path,
dt,
tm
)
)
if response.status_int == 200:
tender_list = munchify(loads(response.body_string()))
self._update_params(tender_list.next_page)
return tender_list.data
raise InvalidResponse
def _get_tender_resource_list(self, tender_id, items_name, access_token=None):
if not access_token:
access_token = ""
return self._get_resource_item(
'{}/{}/{}'.format(self.prefix_path, tender_id, items_name),
headers={'X-Access-Token':access_token}
)
def get_questions(self, tender_id, params={}, access_token=None):
return self._get_tender_resource_list(tender_id, "questions", access_token)
def get_documents(self, tender_id, params={}, access_token=None):
return self._get_tender_resource_list(tender_id, "documents", access_token)
def get_awards(self, tender_id, params={}, access_token=None):
return self._get_tender_resource_list(tender_id, "awards", access_token)
def get_lots(self, tender_id, params={}, access_token=None):
return self._get_tender_resource_list(tender_id, "lots", access_token)
###########################################################################
# CREATE ITEM API METHODS
###########################################################################
def _create_resource_item(self, url, payload, headers={}):
headers.update(self.headers)
response_item = self.post(
url, headers=headers, payload=dumps(payload)
)
if response_item.status_int == 201:
return munchify(loads(response_item.body_string()))
raise InvalidResponse
def _create_tender_resource_item(self, tender_id, item_obj, items_name, access_token=None):
if not access_token:
access_token = ""
return self._create_resource_item(
'{}/{}/{}'.format(self.prefix_path, tender_id, items_name),
item_obj,
headers={'X-Access-Token':access_token}
)
def create_tender(self, tender_id):
return self._create_resource_item(self.prefix_path, tender)
def create_question(self, tender_id, question, access_token=None):
return self._create_tender_resource_item(tender_id, question, "questions", access_token)
def create_bid(self, tender_id, bid, access_token=None):
return self._create_tender_resource_item(tender_id, bid, "bids", access_token)
def create_lot(self, tender_id, lot, access_token=None):
return self._create_tender_resource_item(tender_id, lot, "lots", access_token)
def create_award(self, tender_id, award, access_token=None):
return self._create_tender_resource_item(tender_id, award, "awards", access_token)
def create_cancellation(self, tender_id, cancellation, access_token=None):
return self._create_tender_resource_item(tender_id, cancellation, "cancellations", access_token)
###########################################################################
# GET ITEM API METHODS
###########################################################################
def _get_resource_item(self, url, headers={}):
headers.update(self.headers)
response_item = self.get(url, headers=headers)
if response_item.status_int == 200:
return munchify(loads(response_item.body_string()))
raise InvalidResponse
def get_tender(self, id):
return self._get_resource_item('{}/{}'.format(self.prefix_path, id))
def _get_tender_resource_item(self, tender_id, item_id, items_name,
access_token=None):
if not access_token:
access_token = ""
return self._get_resource_item(
'{}/{}/{}/{}'.format(self.prefix_path,
tender_id,
items_name,
item_id),
headers={'X-Access-Token': access_token}
)
def get_question(self, tender_id, question_id, access_token=None):
return self._get_tender_resource_item(tender_id, question_id, "questions", access_token)
def get_bid(self, tender_id, bid_id, access_token=None):
return self._get_tender_resource_item(tender_id, bid_id, "bids", access_token)
def get_lot(self, tender_id, lot_id, access_token=None):
return self._get_tender_resource_item(tender_id, lot_id, "lots", access_token)
def get_file(self, tender, url, access_token):
logger.info("get_file is deprecated. In next update this function will no takes tender.")
parsed_url = urlparse(url)
if access_token:
headers = {'X-Access-Token': access_token}
else:
raise NoToken
headers.update(self.headers)
response_item = self.get(parsed_url.path,
headers=headers,
params_dict=parse_qs(parsed_url.query))
if response_item.status_int == 302:
response_obj = request(response_item.headers['location'])
if response_obj.status_int == 200:
return response_obj.body_string(), \
response_obj.headers['Content-Disposition'] \
.split(";")[1].split('"')[1]
raise InvalidResponse
###########################################################################
# PATCH ITEM API METHODS
###########################################################################
def _patch_resource_item(self, url, payload, headers={}):
headers.update(self.headers)
response_item = self.patch(
url, headers=headers, payload=dumps(payload)
)
if response_item.status_int == 200:
return munchify(loads(response_item.body_string()))
raise InvalidResponse
def _patch_tender_resource_item(self, tender_id, item_obj, items_name, access_token):
return self._patch_resource_item(
'{}/{}/{}/{}'.format(
self.prefix_path, tender_id, items_name, item_obj['data']['id']
),
payload=item_obj,
headers={'X-Access-Token':access_token}
)
def patch_tender(self, tender):
return self._patch_resource_item(
'{}/{}'.format(self.prefix_path, tender["data"]["id"]),
payload=tender,
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
def patch_question(self, tender_id, question, access_token):
return self._patch_tender_resource_item(tender_id, question, "questions", access_token)
def patch_bid(self, tender_id, bid, access_token):
return self._patch_tender_resource_item(tender_id, bid, "bids", access_token)
def patch_qualification(self, tender_id, qualification, access_token):
return self._patch_tender_resource_item(tender_id, qualification, "qualifications", access_token)
def patch_award(self, tender_id, award, access_token):
return self._patch_tender_resource_item(tender_id, award, "awards", access_token)
def patch_cancellation(self, tender_id, cancellation, access_token):
return self._patch_tender_resource_item(tender_id, cancellation, "cancellations", access_token)
def patch_cancellation_document(self, tender, cancellation_data, cancel_num, doc_num):
cancel_num = int(cancel_num)
doc_num = int(doc_num)
return self._patch_resource_item(
'{}/{}/{}/{}/documents/{}'.format(
self.prefix_path, tender.data.id, "cancellations", tender['data']['cancellations'][cancel_num]['id'], tender['data']['cancellations'][cancel_num]['documents'][doc_num]['id']
),
payload=cancellation_data,
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
def patch_lot(self, tender_id, lot, access_token):
return self._patch_tender_resource_item(tender_id, lot, "lots", access_token)
def patch_document(self, tender_id, document, access_token):
return self._patch_tender_resource_item(tender_id, document, "documents", access_token)
def patch_contract(self, tender_id, contract, access_token):
return self._patch_tender_resource_item(tender_id, contract, "contracts", access_token)
###########################################################################
# UPLOAD FILE API METHODS
###########################################################################
def _upload_resource_file(self, url, data, headers={}, method='post'):
file_headers = {}
file_headers.update(self.headers)
file_headers.update(headers)
file_headers['Content-Type'] = "multipart/form-data"
response_item = getattr(self, method)(
url, headers=file_headers, payload=data
)
if response_item.status_int in (201, 200):
return munchify(loads(response_item.body_string()))
raise InvalidResponse
@verify_file
def upload_document(self, file_, tender_id, access_token):
return self._upload_resource_file(
'{}/{}/documents'.format(
self.prefix_path,
tender_id
),
data={"file": file_},
headers={'X-Access-Token':access_token}
)
@verify_file
def upload_bid_document(self, file_, tender_id, bid_id, access_token):
return self._upload_resource_file(
'{}/{}/bids/{}/documents'.format(
self.prefix_path,
tender_id,
bid_id
),
data={"file": file_},
headers={'X-Access-Token':access_token}
)
@verify_file
def update_bid_document(self, file_, tender_id, bid_id, document_id, access_token):
return self._upload_resource_file(
'{}/{}/bids/{}/documents/{}'.format(
self.prefix_path,
tender_id,
bid_id,
document_id
),
data={"file": file_},
headers={'X-Access-Token':access_token},
method='put'
)
@verify_file
def upload_cancellation_document(self, file_, tender_id, cancellation_id, access_token):
return self._upload_resource_file(
'{}/{}/cancellations/{}/documents'.format(
self.prefix_path,
tender_id,
cancellation_id
),
data={"file": file_},
headers={'X-Access-Token':access_token}
)
@verify_file
def update_cancellation_document(self, file_, tender_id, cancellation_id, document_id, access_token):
return self._upload_resource_file(
'{}/{}/cancellations/{}/documents/{}'.format(
self.prefix_path,
tender_id,
cancellation_id,
document_id
),
data={"file": file_},
headers={'X-Access-Token':access_token},
method='put'
)
###########################################################################
# DELETE ITEMS LIST API METHODS
###########################################################################
def _delete_resource_item(self, url, headers={}):
response_item = self.delete(url, headers=headers)
if response_item.status_int == 200:
return munchify(loads(response_item.body_string()))
raise InvalidResponse
def delete_bid(self, tender_id, bid_id, access_token):
return self._delete_resource_item(
'{}/{}/bids/{}'.format(
self.prefix_path,
tender_id,
bid_id
),
headers={'X-Access-Token': access_token}
)
def delete_lot(self, tender_id, lot_id, access_token):
return self._delete_resource_item(
'{}/{}/lots/{}'.format(
self.prefix_path,
tender_id,
lot_id
),
headers={'X-Access-Token':access_token}
)
###########################################################################
| {
"repo_name": "Leits/openprocurement.client.python",
"path": "openprocurement_client/client.py",
"copies": "1",
"size": "17177",
"license": "apache-2.0",
"hash": 2524530353353194500,
"line_mean": 38.5783410138,
"line_max": 189,
"alpha_frac": 0.5390347558,
"autogenerated": false,
"ratio": 4.130079345996633,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5169114101796634,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from iso8601 import parse_date
from munch import munchify
from restkit import BasicAuth, request, Resource
from restkit.errors import ResourceNotFound
from retrying import retry
from simplejson import dumps, loads
from urlparse import parse_qs, urlparse
import logging
from openprocurement_client.exceptions import InvalidResponse, NoToken
logger = logging.getLogger(__name__)
IGNORE_PARAMS = ('uri', 'path')
def verify_file(fn):
@wraps(fn)
def wrapper(self, file_, *args, **kwargs):
if isinstance(file_, str):
file_ = open(file_, 'rb')
if hasattr(file_, 'read'):
# A file-like object must have 'read' method
return fn(self, file_, *args, **kwargs)
else:
raise TypeError('Expected either a string '
'containing a path to file or a '
'file-like object, got {}'.format(type(file_)))
return wrapper
class APIBaseClient(Resource):
"""base class for API"""
def __init__(self, key,
host_url,
api_version,
resource,
params=None,
**kwargs):
super(APIBaseClient, self).__init__(
host_url,
filters=[BasicAuth(key, "")],
**kwargs
)
self.prefix_path = '/api/{}/{}'.format(api_version, resource)
if not isinstance(params, dict):
params = {"mode": "_all_"}
self.params = params
self.headers = {"Content-Type": "application/json"}
# To perform some operations (e.g. create a tender)
# we first need to obtain a cookie. For that reason,
# here we send a HEAD request to a neutral URL.
self.head('/api/{}/spore'.format(api_version))
def request(self, method, path=None, payload=None, headers=None,
params_dict=None, **params):
_headers = dict(self.headers)
_headers.update(headers or {})
try:
response = super(APIBaseClient, self).request(
method, path=path, payload=payload, headers=_headers,
params_dict=params_dict, **params
)
if 'Set-Cookie' in response.headers:
self.headers['Cookie'] = response.headers['Set-Cookie']
return response
except ResourceNotFound as e:
if 'Set-Cookie' in e.response.headers:
self.headers['Cookie'] = e.response.headers['Set-Cookie']
raise e
def patch(self, path=None, payload=None, headers=None,
params_dict=None, **params):
""" HTTP PATCH
- payload: string passed to the body of the request
- path: string additionnal path to the uri
- headers: dict, optionnal headers that will
be added to HTTP request.
- params: Optionnal parameterss added to the request
"""
return self.request("PATCH", path=path, payload=payload,
headers=headers, params_dict=params_dict, **params)
def delete(self, path=None, headers=None):
""" HTTP DELETE
- path: string additionnal path to the uri
- headers: dict, optionnal headers that will
be added to HTTP request.
- params: Optionnal parameterss added to the request
"""
return self.request("DELETE", path=path, headers=headers)
def _update_params(self, params):
for key in params:
if key not in IGNORE_PARAMS:
self.params[key] = params[key]
def _create_resource_item(self, url, payload, headers={}):
headers.update(self.headers)
response_item = self.post(
url, headers=headers, payload=dumps(payload)
)
if response_item.status_int == 201:
return munchify(loads(response_item.body_string()))
raise InvalidResponse
def _get_resource_item(self, url, headers={}):
headers.update(self.headers)
response_item = self.get(url, headers=headers)
if response_item.status_int == 200:
return munchify(loads(response_item.body_string()))
raise InvalidResponse
def _patch_resource_item(self, url, payload, headers={}):
headers.update(self.headers)
response_item = self.patch(
url, headers=headers, payload=dumps(payload)
)
if response_item.status_int == 200:
return munchify(loads(response_item.body_string()))
raise InvalidResponse
def _upload_resource_file(self, url, data, headers={}, method='post'):
file_headers = {}
file_headers.update(self.headers)
file_headers.update(headers)
file_headers['Content-Type'] = "multipart/form-data"
response_item = getattr(self, method)(
url, headers=file_headers, payload=data
)
if response_item.status_int in (201, 200):
return munchify(loads(response_item.body_string()))
raise InvalidResponse
def _delete_resource_item(self, url, headers={}):
response_item = self.delete(url, headers=headers)
if response_item.status_int == 200:
return munchify(loads(response_item.body_string()))
raise InvalidResponse
class TendersClient(APIBaseClient):
"""client for tenders"""
def __init__(self, key,
host_url="https://api-sandbox.openprocurement.org",
api_version='2.0',
params=None):
super(TendersClient, self).__init__(key, host_url,api_version, "tenders", params)
###########################################################################
# GET ITEMS LIST API METHODS
###########################################################################
@retry(stop_max_attempt_number=5)
def get_tenders(self, params={}, feed='changes'):
params['feed'] = feed
try:
self._update_params(params)
response = self.get(
self.prefix_path,
params_dict=self.params)
if response.status_int == 200:
tender_list = munchify(loads(response.body_string()))
self._update_params(tender_list.next_page)
return tender_list.data
except ResourceNotFound:
del self.params['offset']
raise
raise InvalidResponse
def get_latest_tenders(self, date, tender_id):
iso_dt = parse_date(date)
dt = iso_dt.strftime("%Y-%m-%d")
tm = iso_dt.strftime("%H:%M:%S")
response = self._get_resource_item(
'{}?offset={}T{}&opt_fields=tender_id&mode=test'.format(
self.prefix_path,
dt,
tm
)
)
if response.status_int == 200:
tender_list = munchify(loads(response.body_string()))
self._update_params(tender_list.next_page)
return tender_list.data
raise InvalidResponse
def _get_tender_resource_list(self, tender, items_name):
return self._get_resource_item(
'{}/{}/{}'.format(self.prefix_path, tender.data.id, items_name),
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
def get_questions(self, tender, params={}):
return self._get_tender_resource_list(tender, "questions")
def get_documents(self, tender, params={}):
return self._get_tender_resource_list(tender, "documents")
def get_awards(self, tender, params={}):
return self._get_tender_resource_list(tender, "awards")
def get_lots(self, tender, params={}):
return self._get_tender_resource_list(tender, "lots")
###########################################################################
# CREATE ITEM API METHODS
###########################################################################
def _create_tender_resource_item(self, tender, item_obj, items_name):
return self._create_resource_item(
'{}/{}/{}'.format(self.prefix_path, tender.data.id, items_name),
item_obj,
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
def create_tender(self, tender):
return self._create_resource_item(self.prefix_path, tender)
def create_question(self, tender, question):
return self._create_tender_resource_item(tender, question, "questions")
def create_bid(self, tender, bid):
return self._create_tender_resource_item(tender, bid, "bids")
def create_lot(self, tender, lot):
return self._create_tender_resource_item(tender, lot, "lots")
def create_award(self, tender, award):
return self._create_tender_resource_item(tender, award, "awards")
def create_cancellation(self, tender, cancellation):
return self._create_tender_resource_item(tender, cancellation, "cancellations")
def create_complaint(self, tender, complaint):
return self._create_tender_resource_item(tender, complaint, "complaints")
def create_award_complaint(self, tender, complaint, award_id):
return self._create_resource_item(
'{}/{}/{}'.format(self.prefix_path, tender.data.id, "awards/{0}/complaints".format(award_id)),
complaint,
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
###########################################################################
# GET ITEM API METHODS
###########################################################################
def get_tender(self, id):
return self._get_resource_item('{}/{}'.format(self.prefix_path, id))
def _get_tender_resource_item(self, tender, item_id, items_name,
access_token=""):
if access_token:
headers = {'X-Access-Token': access_token}
else:
headers = {'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
return self._get_resource_item(
'{}/{}/{}/{}'.format(self.prefix_path,
tender.data.id,
items_name,
item_id),
headers=headers
)
def get_question(self, tender, question_id):
return self._get_tender_resource_item(tender, question_id, "questions")
def get_bid(self, tender, bid_id, access_token):
return self._get_tender_resource_item(tender, bid_id, "bids",
access_token)
def get_lot(self, tender, lot_id):
return self._get_tender_resource_item(tender, lot_id, "lots")
def get_file(self, tender, url, access_token):
parsed_url = urlparse(url)
if access_token:
headers = {'X-Access-Token': access_token}
else:
raise NoToken
headers.update(self.headers)
response_item = self.get(parsed_url.path,
headers=headers,
params_dict=parse_qs(parsed_url.query))
if response_item.status_int == 302:
response_obj = request(response_item.headers['location'])
if response_obj.status_int == 200:
return response_obj.body_string(), \
response_obj.headers['Content-Disposition'] \
.split(";")[1].split('"')[1]
raise InvalidResponse
def extract_credentials(self, id):
return self._get_resource_item('{}/{}/extract_credentials'.format(self.prefix_path, id))
###########################################################################
# PATCH ITEM API METHODS
###########################################################################
def _patch_tender_resource_item(self, tender, item_obj, items_name):
return self._patch_resource_item(
'{}/{}/{}/{}'.format(
self.prefix_path, tender.data.id, items_name, item_obj['data']['id']
),
payload=item_obj,
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
def patch_tender(self, tender):
return self._patch_resource_item(
'{}/{}'.format(self.prefix_path, tender["data"]["id"]),
payload=tender,
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
def patch_question(self, tender, question):
return self._patch_tender_resource_item(tender, question, "questions")
def patch_bid(self, tender, bid):
return self._patch_tender_resource_item(tender, bid, "bids")
def patch_bid_document(self, tender, document_data, bid_id, document_id):
return self._patch_resource_item(
'{}/{}/{}/{}/documents/{}'.format(
self.prefix_path, tender.data.id, "bids", bid_id, document_id
),
payload=document_data,
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
def patch_award(self, tender, award):
return self._patch_tender_resource_item(tender, award, "awards")
def patch_cancellation(self, tender, cancellation):
return self._patch_tender_resource_item(tender, cancellation, "cancellations")
def patch_cancellation_document(self, tender, cancellation, cancellation_id, cancellation_doc_id):
return self._patch_resource_item(
'{}/{}/{}/{}/documents/{}'.format(
self.prefix_path, tender.data.id, "cancellations", cancellation_id, cancellation_doc_id
),
payload=cancellation,
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
def patch_complaint(self, tender, complaint):
return self._patch_tender_resource_item(tender, complaint, "complaints")
def patch_award_complaint(self, tender, complaint, award_id):
return self._patch_resource_item(
'{}/{}/awards/{}/complaints/{}'.format(
self.prefix_path, tender.data.id, award_id, complaint.data.id
),
payload=complaint,
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
def patch_lot(self, tender, lot):
return self._patch_tender_resource_item(tender, lot, "lots")
def patch_document(self, tender, document):
return self._patch_tender_resource_item(tender, document, "documents")
def patch_qualification(self, tender, qualification):
return self._patch_tender_resource_item(tender, qualification, "qualifications")
def patch_contract(self, tender, contract):
return self._patch_tender_resource_item(tender, contract, "contracts")
###########################################################################
# UPLOAD FILE API METHODS
###########################################################################
@verify_file
def upload_document(self, file_, tender):
return self._upload_resource_file(
'{}/{}/documents'.format(
self.prefix_path,
tender.data.id
),
data={"file": file_},
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
@verify_file
def upload_bid_document(self, file_, tender, bid_id, doc_type="documents"):
return self._upload_resource_file(
'{}/{}/bids/{}/{}'.format(
self.prefix_path,
tender.data.id,
bid_id,
doc_type
),
data={"file": file_},
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
@verify_file
def update_bid_document(self, file_, tender, bid_id, document_id, doc_type="documents"):
return self._upload_resource_file(
'{}/{}/bids/{}/{}/{}'.format(
self.prefix_path,
tender.data.id,
bid_id,
doc_type,
document_id
),
data={"file": file_},
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')},
method='put'
)
@verify_file
def upload_cancellation_document(self, file_, tender, cancellation_id):
return self._upload_resource_file(
'{}/{}/cancellations/{}/documents'.format(
self.prefix_path,
tender.data.id,
cancellation_id
),
data={"file": file_},
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
@verify_file
def update_cancellation_document(self, file_, tender, cancellation_id, document_id):
return self._upload_resource_file(
'{}/{}/cancellations/{}/documents/{}'.format(
self.prefix_path,
tender.data.id,
cancellation_id,
document_id
),
data={"file": file_},
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')},
method='put'
)
@verify_file
def upload_complaint_document(self, file_, tender, complaint_id):
return self._upload_resource_file(
'{}/{}/complaints/{}/documents'.format(
self.prefix_path,
tender.data.id,
complaint_id),
data={"file": file_},
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
@verify_file
def upload_award_complaint_document(self, file_, tender, award_id, complaint_id):
return self._upload_resource_file(
'{}/{}/awards/{}/complaints/{}/documents'.format(
self.prefix_path,
tender.data.id,
award_id,
complaint_id),
data={"file": file_},
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
@verify_file
def upload_qualification_document(self, file_, tender, qualification_id):
return self._upload_resource_file(
'{}/{}/qualifications/{}/documents'.format(
self.prefix_path,
tender.data.id,
qualification_id
),
data={"file": file_},
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
@verify_file
def upload_award_document(self, file_, tender, award_id):
return self._upload_resource_file(
'{}/{}/awards/{}/documents'.format(
self.prefix_path,
tender.data.id,
award_id
),
data={"file": file_},
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
###########################################################################
# DELETE ITEMS LIST API METHODS
###########################################################################
def delete_bid(self, tender, bid, access_token=None):
logger.info("delete_lot is deprecated. In next update this function will takes bid_id and access_token instead bid.")
if isinstance(bid, basestring):
bid_id = bid
access_token = access_token
else:
bid_id = bid.data.id
access_token = getattr(getattr(bid, 'access', ''), 'token', '')
return self._delete_resource_item(
'{}/{}/bids/{}'.format(
self.prefix_path,
tender.data.id,
bid_id
),
headers={'X-Access-Token': access_token}
)
def delete_lot(self, tender, lot):
logger.info("delete_lot is deprecated. In next update this function will takes lot_id instead lot.")
if isinstance(lot, basestring):
lot_id = lot
else:
lot_id = lot.data.id
return self._delete_resource_item(
'{}/{}/lots/{}'.format(
self.prefix_path,
tender.data.id,
lot_id
),
headers={'X-Access-Token':
getattr(getattr(tender, 'access', ''), 'token', '')}
)
###########################################################################
class Client(TendersClient):
"""client for tenders for backward compatibility"""
class TendersClientSync(TendersClient):
def sync_tenders(self, params={}, extra_headers={}):
params['feed'] = 'changes'
self.headers.update(extra_headers)
response = self.get(self.prefix_path, params_dict=params)
if response.status_int == 200:
tender_list = munchify(loads(response.body_string()))
return tender_list
@retry(stop_max_attempt_number=5)
def get_tender(self, id, extra_headers={}):
self.headers.update(extra_headers)
return super(TendersClientSync, self).get_tender(id)
| {
"repo_name": "mykhaly/openprocurement.client.python",
"path": "openprocurement_client/client.py",
"copies": "1",
"size": "21785",
"license": "apache-2.0",
"hash": -949141567483230700,
"line_mean": 37.4215167549,
"line_max": 125,
"alpha_frac": 0.5239843929,
"autogenerated": false,
"ratio": 4.202353395061729,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00046889818482407324,
"num_lines": 567
} |
from functools import wraps
from itertools import chain
from numpy import linspace, meshgrid, sort, unique
from scipy.interpolate import griddata
"""
Generic tools.
"""
def flatten(iterable):
"""
Flatten an iterable by one level.
"""
return chain.from_iterable(iterable)
def sift(items, cls):
"""
Filter out items which are not instances of cls.
"""
return [item for item in items if isinstance(item, cls)]
def triples_to_mesh(x, y, z):
"""
Convert 3 equal-sized lists of co-ordinates into an interpolated 2D mesh of z-values.
Returns a tuple of:
the mesh
the x bounds
the y bounds
the z bounds
"""
x_values, y_values = sort(unique(x)), sort(unique(y))
x_space = linspace(x_values[0], x_values[-1], len(x_values))
y_space = linspace(y_values[0], y_values[-1], len(y_values))
target_x, target_y = meshgrid(x_space, y_space)
target_z = griddata((x, y), z, (target_x, target_y), method='cubic')
return (target_z, (x_values[0], x_values[-1]), (y_values[0], y_values[-1]),
(min(z), max(z)))
class Enum(set):
"""
An enumerated type.
>>> e = Enum(['a', 'b', 'c'])
>>> e.a
'a'
>>> e.d
...
AttributeError: 'Enum' object has no attribute 'd'
"""
def __getattribute__(self, name):
if name in self:
return name
else:
return set.__getattribute__(self, name)
class PubDict(dict):
"""
A locking, publishing dictionary.
"""
def __init__(self, lock, send, topic, *args, **kwargs):
"""
lock: A re-entrant lock which supports context management.
send: Message-sending method of a PubSub publisher.
topic: The topic on which to send messages.
"""
dict.__init__(self, *args, **kwargs)
self.lock = lock
self.send = send
self.topic = topic
def __setitem__(self, k, v):
"""
Note: Values cannot be overwritten, to ensure that removal is always handled explicitly.
"""
with self.lock:
if k in self:
raise KeyError(k)
if v is None:
raise ValueError('No value given.')
dict.__setitem__(self, k, v)
self.send('{0}.added'.format(self.topic), name=k, value=v)
def __delitem__(self, k):
with self.lock:
dict.__delitem__(self, k)
self.send('{0}.removed'.format(self.topic), name=k)
class Synchronized(object):
"""
A decorator for methods which must be synchronized within an object instance.
"""
@staticmethod
def __call__(f):
@wraps(f)
def decorated(self, *args, **kwargs):
with self.lock:
return f(self, *args, **kwargs)
return decorated
class Without(object):
"""
A no-op object for use with "with".
"""
def __enter__(self, *args, **kwargs):
return None
def __exit__(self, *args, **kwargs):
return False
| {
"repo_name": "0/SpanishAcquisition",
"path": "spacq/tool/box.py",
"copies": "2",
"size": "2649",
"license": "bsd-2-clause",
"hash": -417224187081909400,
"line_mean": 18.6222222222,
"line_max": 90,
"alpha_frac": 0.6436391091,
"autogenerated": false,
"ratio": 2.9531772575250836,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9356173607530214,
"avg_score": 0.04812855181897405,
"num_lines": 135
} |
from functools import wraps
from itertools import chain
from urllib.parse import urlparse
from flask import abort, current_app, g, make_response, request
from flask_login import current_user
from notifications_utils.field import Field
from orderedset._orderedset import OrderedSet
from werkzeug.datastructures import MultiDict
from werkzeug.routing import RequestRedirect
SENDING_STATUSES = ['created', 'pending', 'sending', 'pending-virus-check']
DELIVERED_STATUSES = ['delivered', 'sent', 'returned-letter']
FAILURE_STATUSES = ['failed', 'temporary-failure', 'permanent-failure',
'technical-failure', 'virus-scan-failed', 'validation-failed']
REQUESTED_STATUSES = SENDING_STATUSES + DELIVERED_STATUSES + FAILURE_STATUSES
NOTIFICATION_TYPES = ["sms", "email", "letter", "broadcast"]
def service_has_permission(permission):
from app import current_service
def wrap(func):
@wraps(func)
def wrap_func(*args, **kwargs):
if not current_service or not current_service.has_permission(permission):
abort(403)
return func(*args, **kwargs)
return wrap_func
return wrap
def get_help_argument():
return request.args.get('help') if request.args.get('help') in ('1', '2', '3') else None
def get_logo_cdn_domain():
parsed_uri = urlparse(current_app.config['ADMIN_BASE_URL'])
if parsed_uri.netloc.startswith('localhost'):
return 'static-logos.notify.tools'
subdomain = parsed_uri.hostname.split('.')[0]
domain = parsed_uri.netloc[len(subdomain + '.'):]
return "static-logos.{}".format(domain)
def parse_filter_args(filter_dict):
if not isinstance(filter_dict, MultiDict):
filter_dict = MultiDict(filter_dict)
return MultiDict(
(
key,
(','.join(filter_dict.getlist(key))).split(',')
)
for key in filter_dict.keys()
if ''.join(filter_dict.getlist(key))
)
def set_status_filters(filter_args):
status_filters = filter_args.get('status', [])
return list(OrderedSet(chain(
(status_filters or REQUESTED_STATUSES),
DELIVERED_STATUSES if 'delivered' in status_filters else [],
SENDING_STATUSES if 'sending' in status_filters else [],
FAILURE_STATUSES if 'failed' in status_filters else []
)))
def unicode_truncate(s, length):
encoded = s.encode('utf-8')[:length]
return encoded.decode('utf-8', 'ignore')
def should_skip_template_page(template_type):
return (
current_user.has_permissions('send_messages')
and not current_user.has_permissions('manage_templates', 'manage_api_keys')
and template_type != 'letter'
)
def get_default_sms_sender(sms_senders):
return str(next((
Field(x['sms_sender'], html='escape')
for x in sms_senders if x['is_default']
), "None"))
class PermanentRedirect(RequestRedirect):
"""
In Werkzeug 0.15.0 the status code for RequestRedirect changed from 301 to 308.
308 status codes are not supported when Internet Explorer is used with Windows 7
and Windows 8.1, so this class keeps the original status code of 301.
"""
code = 301
def hide_from_search_engines(f):
@wraps(f)
def decorated_function(*args, **kwargs):
g.hide_from_search_engines = True
response = make_response(f(*args, **kwargs))
response.headers['X-Robots-Tag'] = 'noindex'
return response
return decorated_function
# Function to merge two dict or lists with a JSON-like structure into one.
# JSON-like means they can contain all types JSON can: all the main primitives
# plus nested lists or dictionaries.
# Merge is additive. New values overwrite old and collections are added to.
def merge_jsonlike(source, destination):
def merge_items(source_item, destination_item):
if isinstance(source_item, dict) and isinstance(destination_item, dict):
merge_dicts(source_item, destination_item)
elif isinstance(source_item, list) and isinstance(destination_item, list):
merge_lists(source_item, destination_item)
else: # primitive value
return False
return True
def merge_lists(source, destination):
last_src_idx = len(source) - 1
for idx, item in enumerate(destination):
if idx <= last_src_idx:
# assign destination value if can't be merged into source
if merge_items(source[idx], destination[idx]) is False:
source[idx] = destination[idx]
else:
source.append(item)
def merge_dicts(source, destination):
for key, value in destination.items():
if key in source:
# assign destination value if can't be merged into source
if merge_items(source[key], value) is False:
source[key] = value
else:
source[key] = value
merge_items(source, destination)
| {
"repo_name": "alphagov/notifications-admin",
"path": "app/utils/__init__.py",
"copies": "1",
"size": "5008",
"license": "mit",
"hash": 6326252680721185000,
"line_mean": 33.0680272109,
"line_max": 92,
"alpha_frac": 0.6521565495,
"autogenerated": false,
"ratio": 3.9777601270849883,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5129916676584988,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from itertools import chain
from .compat import Iterable, Mapping
def _with_clone(fn):
@wraps(fn)
def wrapper(self, *args, **kwargs):
clone = self.clone()
res = fn(clone, *args, **kwargs)
if res is not None:
return res
return clone
return wrapper
class cached_property(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, type=None):
if instance is None:
return self
res = instance.__dict__[self.func.__name__] = self.func(instance)
return res
def to_camel_case(s):
return u''.join(map(lambda w: w.capitalize(), s.split('_')))
def clean_params(params, **kwargs):
return {
p: v for p, v in chain(params.items(), kwargs.items())
if v is not None
}
def collect_doc_classes(expr):
if hasattr(expr, '_collect_doc_classes'):
return expr._collect_doc_classes()
if isinstance(expr, dict):
return set().union(
*[collect_doc_classes(e)
for e in chain(expr.keys(), expr.values())]
)
if isinstance(expr, (list, tuple)):
return set().union(*[collect_doc_classes(e) for e in expr])
return set()
def maybe_float(value):
if value is None:
return None
return float(value)
def merge_params(params, args, kwargs):
assert isinstance(args, Iterable), args
assert isinstance(kwargs, Mapping), kwargs
new = dict()
for a in args:
new.update(a)
new.update(kwargs)
return type(params)(params, **new)
| {
"repo_name": "anti-social/elasticmagic",
"path": "elasticmagic/util.py",
"copies": "1",
"size": "1607",
"license": "apache-2.0",
"hash": -3801932500696578600,
"line_mean": 21.9571428571,
"line_max": 73,
"alpha_frac": 0.5930304916,
"autogenerated": false,
"ratio": 3.7811764705882354,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9874206962188236,
"avg_score": 0,
"num_lines": 70
} |
from functools import wraps
from itertools import chain
from django.contrib import messages
from django.contrib.admin.utils import unquote
from django.db.models.query import QuerySet
from django.http import Http404, HttpResponseRedirect
from django.http.response import HttpResponseBase
from django.views.generic import View
from django.views.generic.detail import SingleObjectMixin
from django.views.generic.list import MultipleObjectMixin
try:
from django.urls import re_path
except ImportError:
from django.conf.urls import url as re_path # DJANGO1.11
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse # DJANGO1.10
class BaseDjangoObjectActions(object):
"""
ModelAdmin mixin to add new actions just like adding admin actions.
Attributes
----------
model : django.db.models.Model
The Django Model these actions work on. This is populated by Django.
change_actions : list of str
Write the names of the methods of the model admin that can be used as
tools in the change view.
changelist_actions : list of str
Write the names of the methods of the model admin that can be used as
tools in the changelist view.
tools_view_name : str
The name of the Django Object Actions admin view, including the 'admin'
namespace. Populated by `_get_action_urls`.
"""
change_actions = []
changelist_actions = []
tools_view_name = None
# EXISTING ADMIN METHODS MODIFIED
#################################
def get_urls(self):
"""Prepend `get_urls` with our own patterns."""
urls = super(BaseDjangoObjectActions, self).get_urls()
return self._get_action_urls() + urls
def change_view(self, request, object_id, form_url="", extra_context=None):
extra_context = extra_context or {}
extra_context.update(
{
"objectactions": [
self._get_tool_dict(action)
for action in self.get_change_actions(request, object_id, form_url)
],
"tools_view_name": self.tools_view_name,
}
)
return super(BaseDjangoObjectActions, self).change_view(
request, object_id, form_url, extra_context
)
def changelist_view(self, request, extra_context=None):
extra_context = extra_context or {}
extra_context.update(
{
"objectactions": [
self._get_tool_dict(action)
for action in self.get_changelist_actions(request)
],
"tools_view_name": self.tools_view_name,
}
)
return super(BaseDjangoObjectActions, self).changelist_view(
request, extra_context
)
# USER OVERRIDABLE
##################
def get_change_actions(self, request, object_id, form_url):
"""
Override this to customize what actions get to the change view.
This takes the same parameters as `change_view`.
For example, to restrict actions to superusers, you could do:
class ChoiceAdmin(DjangoObjectActions, admin.ModelAdmin):
def get_change_actions(self, request, **kwargs):
if request.user.is_superuser:
return super(ChoiceAdmin, self).get_change_actions(
request, **kwargs
)
return []
"""
return self.change_actions
def get_changelist_actions(self, request):
"""
Override this to customize what actions get to the changelist view.
"""
return self.changelist_actions
# INTERNAL METHODS
##################
def _get_action_urls(self):
"""Get the url patterns that route each action to a view."""
actions = {}
model_name = self.model._meta.model_name
# e.g.: polls_poll
base_url_name = "%s_%s" % (self.model._meta.app_label, model_name)
# e.g.: polls_poll_actions
model_actions_url_name = "%s_actions" % base_url_name
self.tools_view_name = "admin:" + model_actions_url_name
# WISHLIST use get_change_actions and get_changelist_actions
# TODO separate change and changelist actions
for action in chain(self.change_actions, self.changelist_actions):
actions[action] = getattr(self, action)
return [
# change, supports the same pks the admin does
# https://github.com/django/django/blob/stable/1.10.x/django/contrib/admin/options.py#L555
re_path(
r"^(?P<pk>.+)/actions/(?P<tool>\w+)/$",
self.admin_site.admin_view( # checks permissions
ChangeActionView.as_view(
model=self.model,
actions=actions,
back="admin:%s_change" % base_url_name,
current_app=self.admin_site.name,
)
),
name=model_actions_url_name,
),
# changelist
re_path(
r"^actions/(?P<tool>\w+)/$",
self.admin_site.admin_view( # checks permissions
ChangeListActionView.as_view(
model=self.model,
actions=actions,
back="admin:%s_changelist" % base_url_name,
current_app=self.admin_site.name,
)
),
# Dupe name is fine. https://code.djangoproject.com/ticket/14259
name=model_actions_url_name,
),
]
def _get_tool_dict(self, tool_name):
"""Represents the tool as a dict with extra meta."""
tool = getattr(self, tool_name)
standard_attrs, custom_attrs = self._get_button_attrs(tool)
return dict(
name=tool_name,
label=getattr(tool, "label", tool_name.replace("_", " ").capitalize()),
standard_attrs=standard_attrs,
custom_attrs=custom_attrs,
)
def _get_button_attrs(self, tool):
"""
Get the HTML attributes associated with a tool.
There are some standard attributes (class and title) that the template
will always want. Any number of additional attributes can be specified
and passed on. This is kinda awkward and due for a refactor for
readability.
"""
attrs = getattr(tool, "attrs", {})
# href is not allowed to be set. should an exception be raised instead?
if "href" in attrs:
attrs.pop("href")
# title is not allowed to be set. should an exception be raised instead?
# `short_description` should be set instead to parallel django admin
# actions
if "title" in attrs:
attrs.pop("title")
default_attrs = {
"class": attrs.get("class", ""),
"title": getattr(tool, "short_description", ""),
}
standard_attrs = {}
custom_attrs = {}
for k, v in dict(default_attrs, **attrs).items():
if k in default_attrs:
standard_attrs[k] = v
else:
custom_attrs[k] = v
return standard_attrs, custom_attrs
class DjangoObjectActions(BaseDjangoObjectActions):
change_form_template = "django_object_actions/change_form.html"
change_list_template = "django_object_actions/change_list.html"
class BaseActionView(View):
"""
The view that runs a change/changelist action callable.
Attributes
----------
back : str
The urlpattern name to send users back to. This is set in
`_get_action_urls` and turned into a url with the `back_url` property.
model : django.db.model.Model
The model this tool operates on.
actions : dict
A mapping of action names to callables.
"""
back = None
model = None
actions = None
current_app = None
@property
def view_args(self):
"""
tuple: The argument(s) to send to the action (excluding `request`).
Change actions are called with `(request, obj)` while changelist
actions are called with `(request, queryset)`.
"""
raise NotImplementedError
@property
def back_url(self):
"""
str: The url path the action should send the user back to.
If an action does not return a http response, we automagically send
users back to either the change or the changelist page.
"""
raise NotImplementedError
def get(self, request, tool, **kwargs):
# Fix for case if there are special symbols in object pk
for k, v in self.kwargs.items():
self.kwargs[k] = unquote(v)
try:
view = self.actions[tool]
except KeyError:
raise Http404("Action does not exist")
ret = view(request, *self.view_args)
if isinstance(ret, HttpResponseBase):
return ret
return HttpResponseRedirect(self.back_url)
# HACK to allow POST requests too
post = get
def message_user(self, request, message):
"""
Mimic Django admin actions's `message_user`.
Like the second example:
https://docs.djangoproject.com/en/1.9/ref/contrib/admin/actions/#custom-admin-action
"""
messages.info(request, message)
class ChangeActionView(SingleObjectMixin, BaseActionView):
@property
def view_args(self):
return (self.get_object(),)
@property
def back_url(self):
return reverse(
self.back, args=(self.kwargs["pk"],), current_app=self.current_app
)
class ChangeListActionView(MultipleObjectMixin, BaseActionView):
@property
def view_args(self):
return (self.get_queryset(),)
@property
def back_url(self):
return reverse(self.back, current_app=self.current_app)
def takes_instance_or_queryset(func):
"""Decorator that makes standard Django admin actions compatible."""
@wraps(func)
def decorated_function(self, request, queryset):
# func follows the prototype documented at:
# https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#writing-action-functions
if not isinstance(queryset, QuerySet):
try:
# Django >=1.8
queryset = self.get_queryset(request).filter(pk=queryset.pk)
except AttributeError:
try:
# Django >=1.6,<1.8
model = queryset._meta.model
except AttributeError: # pragma: no cover
# Django <1.6
model = queryset._meta.concrete_model
queryset = model.objects.filter(pk=queryset.pk)
return func(self, request, queryset)
return decorated_function
| {
"repo_name": "crccheck/django-object-actions",
"path": "django_object_actions/utils.py",
"copies": "1",
"size": "11068",
"license": "apache-2.0",
"hash": -418324101309724500,
"line_mean": 33.3726708075,
"line_max": 102,
"alpha_frac": 0.5849295266,
"autogenerated": false,
"ratio": 4.399046104928458,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00014894334252512308,
"num_lines": 322
} |
from functools import wraps
from itertools import chain
from django.db.models import Prefetch, Q
from django.urls import Resolver404, resolve
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound, ParseError, PermissionDenied, ValidationError
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet, ViewSet
from shapely import prepared
from shapely.ops import cascaded_union
from c3nav.api.utils import get_api_post_data
from c3nav.editor.forms import ChangeSetForm, RejectForm
from c3nav.editor.models import ChangeSet
from c3nav.editor.utils import LevelChildEditUtils, SpaceChildEditUtils
from c3nav.editor.views.base import etag_func
from c3nav.mapdata.api import api_etag
from c3nav.mapdata.models import Area, MapUpdate, Source
from c3nav.mapdata.models.geometry.space import POI
from c3nav.mapdata.utils.user import can_access_editor
class EditorViewSetMixin(ViewSet):
def initial(self, request, *args, **kwargs):
if not can_access_editor(request):
raise PermissionDenied
return super().initial(request, *args, **kwargs)
def api_etag_with_update_cache_key(**outkwargs):
outkwargs.setdefault('cache_kwargs', {})['update_cache_key_match'] = bool
def wrapper(func):
func = api_etag(**outkwargs)(func)
@wraps(func)
def wrapped_func(self, request, *args, **kwargs):
try:
changeset = request.changeset
except AttributeError:
changeset = ChangeSet.get_for_request(request)
request.changeset = changeset
update_cache_key = request.changeset.raw_cache_key_without_changes
update_cache_key_match = request.GET.get('update_cache_key') == update_cache_key
return func(self, request, *args,
update_cache_key=update_cache_key, update_cache_key_match=update_cache_key_match,
**kwargs)
return wrapped_func
return wrapper
class EditorViewSet(EditorViewSetMixin, ViewSet):
"""
Editor API
/geometries/ returns a list of geojson features, you have to specify ?level=<id> or ?space=<id>
/geometrystyles/ returns styling information for all geometry types
/bounds/ returns the maximum bounds of the map
/{path}/ insert an editor path to get an API represantation of it. POST requests on forms are possible as well
"""
lookup_field = 'path'
lookup_value_regex = r'.+'
@staticmethod
def _get_level_geometries(level):
buildings = level.buildings.all()
buildings_geom = cascaded_union([building.geometry for building in buildings])
spaces = {space.pk: space for space in level.spaces.all()}
holes_geom = []
for space in spaces.values():
if space.outside:
space.geometry = space.geometry.difference(buildings_geom)
columns = [column.geometry for column in space.columns.all()]
if columns:
columns_geom = cascaded_union([column.geometry for column in space.columns.all()])
space.geometry = space.geometry.difference(columns_geom)
holes = [hole.geometry for hole in space.holes.all()]
if holes:
space_holes_geom = cascaded_union(holes)
holes_geom.append(space_holes_geom.intersection(space.geometry))
space.geometry = space.geometry.difference(space_holes_geom)
for building in buildings:
building.original_geometry = building.geometry
if holes_geom:
holes_geom = cascaded_union(holes_geom)
holes_geom_prep = prepared.prep(holes_geom)
for obj in buildings:
if holes_geom_prep.intersects(obj.geometry):
obj.geometry = obj.geometry.difference(holes_geom)
results = []
results.extend(buildings)
for door in level.doors.all():
results.append(door)
results.extend(spaces.values())
return results
@staticmethod
def _get_levels_pk(request, level):
# noinspection PyPep8Naming
Level = request.changeset.wrap_model('Level')
levels_under = ()
levels_on_top = ()
lower_level = level.lower(Level).first()
primary_levels = (level,) + ((lower_level,) if lower_level else ())
secondary_levels = Level.objects.filter(on_top_of__in=primary_levels).values_list('pk', 'on_top_of')
if lower_level:
levels_under = tuple(pk for pk, on_top_of in secondary_levels if on_top_of == lower_level.pk)
if True:
levels_on_top = tuple(pk for pk, on_top_of in secondary_levels if on_top_of == level.pk)
levels = chain([level.pk], levels_under, levels_on_top)
return levels, levels_on_top, levels_under
@staticmethod
def area_sorting_func(area):
groups = tuple(area.groups.all())
if not groups:
return (0, 0, 0)
return (1, groups[0].category.priority, groups[0].hierarchy, groups[0].priority)
# noinspection PyPep8Naming
@action(detail=False, methods=['get'])
@api_etag_with_update_cache_key(etag_func=etag_func, cache_parameters={'level': str, 'space': str})
def geometries(self, request, update_cache_key, update_cache_key_match, *args, **kwargs):
Level = request.changeset.wrap_model('Level')
Space = request.changeset.wrap_model('Space')
Column = request.changeset.wrap_model('Column')
Hole = request.changeset.wrap_model('Hole')
AltitudeMarker = request.changeset.wrap_model('AltitudeMarker')
Building = request.changeset.wrap_model('Building')
Door = request.changeset.wrap_model('Door')
LocationGroup = request.changeset.wrap_model('LocationGroup')
WifiMeasurement = request.changeset.wrap_model('WifiMeasurement')
level = request.GET.get('level')
space = request.GET.get('space')
if level is not None:
if space is not None:
raise ValidationError('Only level or space can be specified.')
level = get_object_or_404(Level.objects.filter(Level.q_for_request(request)), pk=level)
edit_utils = LevelChildEditUtils(level, request)
if not edit_utils.can_access_child_base_mapdata:
raise PermissionDenied
levels, levels_on_top, levels_under = self._get_levels_pk(request, level)
# don't prefetch groups for now as changesets do not yet work with m2m-prefetches
levels = Level.objects.filter(pk__in=levels).filter(Level.q_for_request(request))
# graphnodes_qs = request.changeset.wrap_model('GraphNode').objects.all()
levels = levels.prefetch_related(
Prefetch('spaces', Space.objects.filter(Space.q_for_request(request)).only(
'geometry', 'level', 'outside'
)),
Prefetch('doors', Door.objects.filter(Door.q_for_request(request)).only('geometry', 'level')),
Prefetch('spaces__columns', Column.objects.filter(
Q(access_restriction__isnull=True) | ~Column.q_for_request(request)
).only('geometry', 'space')),
Prefetch('spaces__groups', LocationGroup.objects.only(
'color', 'category', 'priority', 'hierarchy', 'category__priority', 'category__allow_spaces'
)),
Prefetch('buildings', Building.objects.only('geometry', 'level')),
Prefetch('spaces__holes', Hole.objects.only('geometry', 'space')),
Prefetch('spaces__altitudemarkers', AltitudeMarker.objects.only('geometry', 'space')),
Prefetch('spaces__wifi_measurements', WifiMeasurement.objects.only('geometry', 'space')),
# Prefetch('spaces__graphnodes', graphnodes_qs)
)
levels = {s.pk: s for s in levels}
level = levels[level.pk]
levels_under = [levels[pk] for pk in levels_under]
levels_on_top = [levels[pk] for pk in levels_on_top]
# todo: permissions
# graphnodes = tuple(chain(*(space.graphnodes.all()
# for space in chain(*(level.spaces.all() for level in levels.values())))))
# graphnodes_lookup = {node.pk: node for node in graphnodes}
# graphedges = request.changeset.wrap_model('GraphEdge').objects.all()
# graphedges = graphedges.filter(Q(from_node__in=graphnodes) | Q(to_node__in=graphnodes))
# graphedges = graphedges.select_related('waytype')
# this is faster because we only deserialize graphnode geometries once
# missing_graphnodes = graphnodes_qs.filter(pk__in=set(chain(*((edge.from_node_id, edge.to_node_id)
# for edge in graphedges))))
# graphnodes_lookup.update({node.pk: node for node in missing_graphnodes})
# for edge in graphedges:
# edge._from_node_cache = graphnodes_lookup[edge.from_node_id]
# edge._to_node_cache = graphnodes_lookup[edge.to_node_id]
# graphedges = [edge for edge in graphedges if edge.from_node.space_id != edge.to_node.space_id]
results = chain(
*(self._get_level_geometries(l) for l in levels_under),
self._get_level_geometries(level),
*(self._get_level_geometries(l) for l in levels_on_top),
*(space.altitudemarkers.all() for space in level.spaces.all()),
*(space.wifi_measurements.all() for space in level.spaces.all())
# graphedges,
# graphnodes,
)
elif space is not None:
space_q_for_request = Space.q_for_request(request)
qs = Space.objects.filter(space_q_for_request)
space = get_object_or_404(qs.select_related('level', 'level__on_top_of'), pk=space)
level = space.level
edit_utils = SpaceChildEditUtils(space, request)
if not edit_utils.can_access_child_base_mapdata:
raise PermissionDenied
if request.user_permissions.can_access_base_mapdata:
doors = [door for door in level.doors.filter(Door.q_for_request(request)).all()
if door.geometry.intersects(space.geometry)]
doors_space_geom = cascaded_union([door.geometry for door in doors]+[space.geometry])
levels, levels_on_top, levels_under = self._get_levels_pk(request, level.primary_level)
if level.on_top_of_id is not None:
levels = chain([level.pk], levels_on_top)
other_spaces = Space.objects.filter(space_q_for_request, level__pk__in=levels).only(
'geometry', 'level'
).prefetch_related(
Prefetch('groups', LocationGroup.objects.only(
'color', 'category', 'priority', 'hierarchy', 'category__priority', 'category__allow_spaces'
).filter(color__isnull=False))
)
space = next(s for s in other_spaces if s.pk == space.pk)
other_spaces = [s for s in other_spaces
if s.geometry.intersects(doors_space_geom) and s.pk != space.pk]
all_other_spaces = other_spaces
if level.on_top_of_id is None:
other_spaces_lower = [s for s in other_spaces if s.level_id in levels_under]
other_spaces_upper = [s for s in other_spaces if s.level_id in levels_on_top]
else:
other_spaces_lower = [s for s in other_spaces if s.level_id == level.on_top_of_id]
other_spaces_upper = []
other_spaces = [s for s in other_spaces if s.level_id == level.pk]
space.bounds = True
# deactivated for performance reasons
buildings = level.buildings.all()
# buildings_geom = cascaded_union([building.geometry for building in buildings])
# for other_space in other_spaces:
# if other_space.outside:
# other_space.geometry = other_space.geometry.difference(buildings_geom)
for other_space in chain(other_spaces, other_spaces_lower, other_spaces_upper):
other_space.opacity = 0.4
other_space.color = '#ffffff'
for building in buildings:
building.opacity = 0.5
else:
buildings = []
doors = []
other_spaces = []
other_spaces_lower = []
other_spaces_upper = []
all_other_spaces = []
# todo: permissions
if request.user_permissions.can_access_base_mapdata:
graphnodes = request.changeset.wrap_model('GraphNode').objects.all()
graphnodes = graphnodes.filter((Q(space__in=all_other_spaces)) | Q(space__pk=space.pk))
space_graphnodes = tuple(node for node in graphnodes if node.space_id == space.pk)
graphedges = request.changeset.wrap_model('GraphEdge').objects.all()
space_graphnodes_ids = tuple(node.pk for node in space_graphnodes)
graphedges = graphedges.filter(Q(from_node__pk__in=space_graphnodes_ids) |
Q(to_node__pk__in=space_graphnodes_ids))
graphedges = graphedges.select_related('from_node', 'to_node', 'waytype').only(
'from_node__geometry', 'to_node__geometry', 'waytype__color'
)
else:
graphnodes = []
graphedges = []
areas = space.areas.filter(Area.q_for_request(request)).only(
'geometry', 'space'
).prefetch_related(
Prefetch('groups', LocationGroup.objects.order_by(
'-category__priority', '-hierarchy', '-priority'
).only(
'color', 'category', 'priority', 'hierarchy', 'category__priority', 'category__allow_areas'
))
)
for area in areas:
area.opacity = 0.5
areas = sorted(areas, key=self.area_sorting_func)
results = chain(
buildings,
other_spaces_lower,
doors,
other_spaces,
[space],
areas,
space.holes.all().only('geometry', 'space'),
space.stairs.all().only('geometry', 'space'),
space.ramps.all().only('geometry', 'space'),
space.obstacles.all().only('geometry', 'space', 'color'),
space.lineobstacles.all().only('geometry', 'width', 'space', 'color'),
space.columns.all().only('geometry', 'space'),
space.altitudemarkers.all().only('geometry', 'space'),
space.wifi_measurements.all().only('geometry', 'space'),
space.pois.filter(POI.q_for_request(request)).only('geometry', 'space').prefetch_related(
Prefetch('groups', LocationGroup.objects.only(
'color', 'category', 'priority', 'hierarchy', 'category__priority', 'category__allow_pois'
).filter(color__isnull=False))
),
other_spaces_upper,
graphedges,
graphnodes
)
else:
raise ValidationError('No level or space specified.')
return Response(list(chain(
[('update_cache_key', update_cache_key)],
(self.conditional_geojson(obj, update_cache_key_match) for obj in results)
)))
def conditional_geojson(self, obj, update_cache_key_match):
if update_cache_key_match and not obj._affected_by_changeset:
return obj.get_geojson_key()
result = obj.to_geojson(instance=obj)
result['properties']['changed'] = obj._affected_by_changeset
return result
@action(detail=False, methods=['get'])
@api_etag(etag_func=MapUpdate.current_cache_key, cache_parameters={})
def geometrystyles(self, request, *args, **kwargs):
return Response({
'building': '#aaaaaa',
'space': '#eeeeee',
'hole': 'rgba(255, 0, 0, 0.3)',
'door': '#ffffff',
'area': '#55aaff',
'stair': '#a000a0',
'ramp': 'rgba(160, 0, 160, 0.2)',
'obstacle': '#999999',
'lineobstacle': '#999999',
'column': 'rgba(0, 0, 50, 0.3)',
'poi': '#4488cc',
'shadow': '#000000',
'graphnode': '#009900',
'graphedge': '#00CC00',
'altitudemarker': '#0000FF',
'wifimeasurement': '#DDDD00',
})
@action(detail=False, methods=['get'])
@api_etag(etag_func=etag_func, cache_parameters={})
def bounds(self, request, *args, **kwargs):
return Response({
'bounds': Source.max_bounds(),
})
def __getattr__(self, name):
# allow POST and DELETE methods for the editor API
if getattr(self, 'get', None).__name__ in ('list', 'retrieve'):
if name == 'post' and (self.resolved.url_name.endswith('.create') or
self.resolved.url_name.endswith('.edit')):
return self.post_or_delete
if name == 'delete' and self.resolved.url_name.endswith('.edit'):
return self.post_or_delete
raise AttributeError
def post_or_delete(self, request, *args, **kwargs):
# django-rest-framework doesn't automatically do this for logged out requests
SessionAuthentication().enforce_csrf(request)
return self.retrieve(request, *args, **kwargs)
def list(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
@cached_property
def resolved(self):
resolved = None
path = self.kwargs.get('path', '')
if path:
try:
resolved = resolve('/editor/'+path+'/')
except Resolver404:
pass
if not resolved:
try:
resolved = resolve('/editor/'+path)
except Resolver404:
pass
self.request.sub_resolver_match = resolved
return resolved
def retrieve(self, request, *args, **kwargs):
resolved = self.resolved
if not resolved:
raise NotFound(_('No matching editor view endpoint found.'))
if not getattr(resolved.func, 'api_hybrid', False):
raise NotFound(_('Matching editor view point does not provide an API.'))
get_api_post_data(request)
response = resolved.func(request, api=True, *resolved.args, **resolved.kwargs)
return response
class ChangeSetViewSet(EditorViewSetMixin, ReadOnlyModelViewSet):
"""
List and manipulate changesets. All lists are ordered by last update descending. Use ?offset= to specify an offset.
Don't forget to set X-Csrftoken for POST requests!
/ lists all changesets this user can see.
/user/ lists changesets by this user
/reviewing/ lists changesets this user is currently reviewing.
/pending_review/ lists changesets this user can review.
/current/ returns the current changeset.
/direct_editing/ POST to activate direct editing (if available).
/deactive/ POST to deactivate current changeset or deactivate direct editing
/{id}/changes/ list all changes of a given changeset.
/{id}/activate/ POST to activate given changeset.
/{id}/edit/ POST to edit given changeset (provide title and description in POST data).
/{id}/restore_object/ POST to restore an object deleted by this changeset (provide change id as id in POST data).
/{id}/delete/ POST to delete given changeset.
/{id}/propose/ POST to propose given changeset.
/{id}/unpropose/ POST to unpropose given changeset.
/{id}/review/ POST to review given changeset.
/{id}/reject/ POST to reject given changeset (provide reject=1 in POST data for final rejection).
/{id}/unreject/ POST to unreject given changeset.
/{id}/apply/ POST to accept and apply given changeset.
"""
queryset = ChangeSet.objects.all()
def get_queryset(self):
return ChangeSet.qs_for_request(self.request).select_related('last_update', 'last_state_update', 'last_change')
def _list(self, request, qs):
offset = 0
if 'offset' in request.GET:
if not request.GET['offset'].isdigit():
raise ParseError('offset has to be a positive integer.')
offset = int(request.GET['offset'])
return Response([obj.serialize() for obj in qs.order_by('-last_update')[offset:offset+20]])
def list(self, request, *args, **kwargs):
return self._list(request, self.get_queryset())
@action(detail=False, methods=['get'])
def user(self, request, *args, **kwargs):
return self._list(request, self.get_queryset().filter(author=request.user))
@action(detail=False, methods=['get'])
def reviewing(self, request, *args, **kwargs):
return self._list(request, self.get_queryset().filter(
assigned_to=request.user, state='review'
))
@action(detail=False, methods=['get'])
def pending_review(self, request, *args, **kwargs):
return self._list(request, self.get_queryset().filter(
state__in=('proposed', 'reproposed'),
))
def retrieve(self, request, *args, **kwargs):
return Response(self.get_object().serialize())
@action(detail=False, methods=['get'])
def current(self, request, *args, **kwargs):
changeset = ChangeSet.get_for_request(request)
return Response({
'direct_editing': changeset.direct_editing,
'changeset': changeset.serialize() if changeset.pk else None,
})
@action(detail=False, methods=['post'])
def direct_editing(self, request, *args, **kwargs):
# django-rest-framework doesn't automatically do this for logged out requests
SessionAuthentication().enforce_csrf(request)
if not ChangeSet.can_direct_edit(request):
raise PermissionDenied(_('You don\'t have the permission to activate direct editing.'))
changeset = ChangeSet.get_for_request(request)
if changeset.pk is not None:
raise PermissionDenied(_('You cannot activate direct editing if you have an active changeset.'))
request.session['direct_editing'] = True
return Response({
'success': True,
})
@action(detail=False, methods=['post'])
def deactivate(self, request, *args, **kwargs):
# django-rest-framework doesn't automatically do this for logged out requests
SessionAuthentication().enforce_csrf(request)
request.session.pop('changeset', None)
request.session['direct_editing'] = False
return Response({
'success': True,
})
@action(detail=True, methods=['get'])
def changes(self, request, *args, **kwargs):
changeset = self.get_object()
changeset.fill_changes_cache()
return Response([obj.serialize() for obj in changeset.iter_changed_objects()])
@action(detail=True, methods=['post'])
def activate(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_activate(request):
raise PermissionDenied(_('You can not activate this change set.'))
changeset.activate(request)
return Response({'success': True})
@action(detail=True, methods=['post'])
def edit(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_edit(request):
raise PermissionDenied(_('You cannot edit this change set.'))
form = ChangeSetForm(instance=changeset, data=get_api_post_data(request))
if not form.is_valid():
raise ParseError(form.errors)
changeset = form.instance
update = changeset.updates.create(user=request.user,
title=changeset.title, description=changeset.description)
changeset.last_update = update
changeset.save()
return Response({'success': True})
@action(detail=True, methods=['post'])
def restore_object(self, request, *args, **kwargs):
data = get_api_post_data(request)
if 'id' not in data:
raise ParseError('Missing id.')
restore_id = data['id']
if isinstance(restore_id, str) and restore_id.isdigit():
restore_id = int(restore_id)
if not isinstance(restore_id, int):
raise ParseError('id needs to be an integer.')
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_edit(request):
raise PermissionDenied(_('You can not edit changes on this change set.'))
try:
changed_object = changeset.changed_objects_set.get(pk=restore_id)
except Exception:
raise NotFound('could not find object.')
try:
changed_object.restore()
except PermissionError:
raise PermissionDenied(_('You cannot restore this object, because it depends on '
'a deleted object or it would violate a unique contraint.'))
return Response({'success': True})
@action(detail=True, methods=['post'])
def propose(self, request, *args, **kwargs):
if not request.user.is_authenticated:
raise PermissionDenied(_('You need to log in to propose changes.'))
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.title or not changeset.description:
raise PermissionDenied(_('You need to add a title an a description to propose this change set.'))
if not changeset.can_propose(request):
raise PermissionDenied(_('You cannot propose this change set.'))
changeset.propose(request.user)
return Response({'success': True})
@action(detail=True, methods=['post'])
def unpropose(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_unpropose(request):
raise PermissionDenied(_('You cannot unpropose this change set.'))
changeset.unpropose(request.user)
return Response({'success': True})
@action(detail=True, methods=['post'])
def review(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_start_review(request):
raise PermissionDenied(_('You cannot review these changes.'))
changeset.start_review(request.user)
return Response({'success': True})
@action(detail=True, methods=['post'])
def reject(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not not changeset.can_end_review(request):
raise PermissionDenied(_('You cannot reject these changes.'))
form = RejectForm(get_api_post_data(request))
if not form.is_valid():
raise ParseError(form.errors)
changeset.reject(request.user, form.cleaned_data['comment'], form.cleaned_data['final'])
return Response({'success': True})
@action(detail=True, methods=['post'])
def unreject(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_unreject(request):
raise PermissionDenied(_('You cannot unreject these changes.'))
changeset.unreject(request.user)
return Response({'success': True})
@action(detail=True, methods=['post'])
def apply(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_end_review(request):
raise PermissionDenied(_('You cannot accept and apply these changes.'))
changeset.apply(request.user)
return Response({'success': True})
@action(detail=True, methods=['post'])
def delete(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_delete(request):
raise PermissionDenied(_('You cannot delete this change set.'))
changeset.delete()
return Response({'success': True})
| {
"repo_name": "c3nav/c3nav",
"path": "src/c3nav/editor/api.py",
"copies": "1",
"size": "29810",
"license": "apache-2.0",
"hash": -6476975307162883000,
"line_mean": 43.6926536732,
"line_max": 119,
"alpha_frac": 0.5983227105,
"autogenerated": false,
"ratio": 4.236180190422055,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0015118481647830593,
"num_lines": 667
} |
from functools import wraps
from itertools import groupby
from operator import itemgetter
from collections import defaultdict
from flask import request
from werkzeug.exceptions import UnsupportedMediaType, NotAcceptable
def build_groups(acceptable):
"""
Build the group information used by the MimeTypeMatcher
Returns a dictionary of String -> Set, which always includes the default
top type "*/*".
"""
ret = defaultdict(lambda: set(['*']))
ret['*'].add('*')
partitioned = (a.partition('/') for a in acceptable)
for group, partsets in groupby(partitioned, itemgetter(0)):
for parts in partsets:
g, sep, species = parts
ret[group].add(species)
return ret
class MimeTypeMatcher(object):
"""
Matcher that contains the logic for deciding if a mimetype is acceptable.
-------------------------------------------------------------------------
One matcher will be constructed for each route, and used to assess the
mimetypes the client can accept, and determine whether this route can
meet the client's requirements.
"""
def __init__(self, acceptable):
self.acceptable = set(str(a) for a in acceptable)
self.groups = build_groups(self.acceptable)
def is_acceptable(self, mimetype):
"""
Test if a given mimetype is acceptable.
"""
mt = str(mimetype)
if mimetype is None or mt.strip() == '':
return False
if mt in self.acceptable:
return True
genus, _, species = mt.partition('/')
if genus in self.groups:
return species in self.groups[genus]
return False
def consumes(*content_types):
def decorated(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if request.mimetype not in content_types:
raise UnsupportedMediaType()
return fn(*args, **kwargs)
return wrapper
return decorated
def produces(*content_types):
"""
Annotate a route as only acceptable for clients that can accept the given
content types.
--------------------------------------------------------------------------
content_types: list of mimetype strings,
example: ["text/html", "application/json"]
Clients that can accept at least one of the given content types will be
allowed to run the route. This means both exact content type matches as
well as wild card matches, so that a client that accepts '*/*' will always
be permitted access, and one that specifies 'text/*' to an HTML route will
also be allowed to proceed.
"""
def decorated(fn):
matcher = MimeTypeMatcher(content_types)
@wraps(fn)
def wrapper(*args, **kwargs):
requested = set(request.accept_mimetypes.values())
acceptable = filter(matcher.is_acceptable, requested)
if len(acceptable) == 0:
raise NotAcceptable()
return fn(*args, **kwargs)
return wrapper
return decorated
| {
"repo_name": "jackfirth/flask-negotiate",
"path": "flask_negotiate2.py",
"copies": "1",
"size": "3060",
"license": "mit",
"hash": 2941254231374739500,
"line_mean": 32.2608695652,
"line_max": 78,
"alpha_frac": 0.6088235294,
"autogenerated": false,
"ratio": 4.751552795031056,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 92
} |
from functools import wraps
from itertools import islice
from contextlib import contextmanager
from collections import Mapping
from copy import copy
from .util import Missing, ExplicitNone, threadlocal
from .hooks import pre_hook, post_hook, Hook
def ContextAttr(name, default=Missing):
def fget(self):
dic = self.__dict__.setdefault('_contextattrs', {})
context = get_context()
if name in dic:
return dic[name]
if default is not Missing:
return context.get(name, default)
try:
return context[name]
except KeyError:
raise AttributeError(name)
def fset(self, value):
dic = self.__dict__.setdefault('_contextattrs', {})
dic[name] = value
return property(fget, fset)
@contextmanager
def add_context(*objects):
added = 0
context = _raw_context()
for obj in objects:
if context.push(obj):
added += 1
context.pending = False
yield
for i in range(added):
context.pop()
@Mapping.register
class ObjectsStack:
def __init__(self, objects=None):
self._objects = objects or []
@property
def objects(self):
return self._objects
def __copy__(self):
return self.__class__(self.objects)
def __repr__(self):
return repr(self.objects)
def __getitem__(self, key):
if isinstance(key, int):
# a bit of user-friendly interface
return self.objects[key]
for obj in self.objects:
try:
if isinstance(obj, Mapping):
return obj[key]
return getattr(obj, key)
except (KeyError, AttributeError):
pass
raise KeyError(key)
def __setitem__(self, key, value):
raise NotImplementedError()
def __delitem__(self, key):
raise NotImplementedError()
def __bool__(self):
return bool(self.objects)
def get(self, key, default=None):
return self[key] if key in self else default
def __contains__(self, key):
try:
self[key]
return True
except KeyError:
pass
def __iter__(self):
yield from self.objects
def __len__(self):
return len(self.objects)
def __eq__(self, other):
if isinstance(other, ObjectsStack):
return self.objects == other.objects
def __ne__(self, other):
return not (self == other)
def push(self, obj):
if obj is not None and obj not in self._objects:
self._objects.insert(0, obj)
return True
def pop(self):
self._objects.pop(0)
class PendingObjectContext(ObjectsStack):
pending = False
@property
def parent(self):
if not self.pending:
return self
objects = islice(self.objects, 1, None)
return self.__class__(tuple(objects))
def _raw_context():
return threadlocal().setdefault('context', PendingObjectContext())
def get_context():
'''
Return parent context.
'''
return _raw_context().parent
class GrabContextWrapper:
def __init__(self, get_context_object):
self.get_context_object = get_context_object
@contextmanager
def as_manager(self, *run_args, **run_kwargs):
context = _raw_context()
was_pending = context.pending
instance = self.get_context_object(*run_args, **run_kwargs)
added = context.push(instance) # whether was added successfully
context.pending = added
yield
if added:
context.pop()
context.pending = was_pending
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
with self.as_manager(*args, **kwargs):
result = None
hook = Hook.lookup((pre_hook, wrapper))
if hook:
result = hook.execute(*args, **kwargs)
if result is None:
# * wrapped function *
result = func(*args, **kwargs)
# * * * * * * * * * *
elif result is ExplicitNone:
result = None
hook = Hook.lookup((post_hook, wrapper))
if hook:
ret = hook.execute(*args, ret=result, **kwargs)
if ret is ExplicitNone:
result = None
elif ret is not None:
result = ret
return result
return wrapper
@GrabContextWrapper
def function(*args, **kwargs):
return None
@GrabContextWrapper
def method(*args, **kwargs):
return args[0]
| {
"repo_name": "abetkin/gcontext",
"path": "gcontext/base.py",
"copies": "1",
"size": "4745",
"license": "mit",
"hash": -4880841745813996000,
"line_mean": 24.6486486486,
"line_max": 71,
"alpha_frac": 0.5527924131,
"autogenerated": false,
"ratio": 4.455399061032864,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5508191474132864,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from itertools import islice
from nose.tools import assert_false
from nose.tools import assert_in
from nose.tools import eq_
from nose.tools import ok_
def _mock_method(function):
function_name = function.func_name
@wraps(function)
def decorator(self, *args, **kwargs):
self._method_calls.append((function_name, args, kwargs))
result = function(self, *args, **kwargs)
return result
return decorator
class MockSerialPort(object):
def __init__(self, writer=None, reader=None):
self._method_calls = []
self._data_writer = writer or MockSerialPortDataWriter()
self._data_reader = reader or MockSerialPortDataReader()
def clear_data(self):
self._data_writer.data_written = ""
self._data_reader.data_read = ""
def assert_method_was_called(self, method_name, *args, **kwargs):
method_calls = \
[call[1:] for call in self._method_calls if call[0] == method_name]
ok_(
method_calls,
"Method {!r} was not called".format(method_name),
)
wrong_arguments_message = \
"Method {!r} was not called with the expected arguments: " \
"Expected: {}".format(
method_name,
(args, kwargs),
)
assert_in(
(args, kwargs),
method_calls,
wrong_arguments_message,
)
def assert_data_was_written(self, expected_data):
if not expected_data.endswith("\n\r"):
expected_data += "\n\r"
actual_data = self._data_writer.data_written
eq_(
expected_data,
actual_data,
"Data {!r} was not written to the port, found {!r}".format(
expected_data,
actual_data,
),
)
def assert_no_data_was_written(self):
actual_data = self._data_writer.data_written
assert_false(
actual_data,
"No data was expected, found {!r}".format(actual_data),
)
def assert_data_was_read(self, data):
if not data.endswith(">"):
data += ">"
eq_(
data,
self._data_reader.data_read,
"Data {!r} was not read from the port".format(data),
)
def assert_scenario(self, *calls):
for expected_call, actual_call in zip(calls, self._method_calls):
expected_method_name, expected_args, expected_kwargs = expected_call
actual_method_name, actual_args, actual_kwargs = actual_call
eq_(
expected_method_name,
actual_method_name,
"Expected call to {!r} found {!r}".format(
expected_method_name,
actual_method_name,
)
)
eq_(
expected_args,
actual_args,
"In call to {!r} expected args {!r} found {!r}".format(
expected_method_name,
expected_args,
actual_args,
)
)
eq_(
expected_args,
actual_args,
"In call to {!r} expected kwargs {!r} found {!r}".format(
expected_method_name,
expected_kwargs,
actual_kwargs,
)
)
@_mock_method
def read(self, size=1):
return self._data_reader.read(size)
@_mock_method
def write(self, data):
self._data_writer.write(data)
@_mock_method
def flushOutput(self):
pass
@_mock_method
def flushInput(self):
pass
@_mock_method
def close(self):
pass
class MockSerialPortDataWriter(object):
def __init__(self):
self.data_written = ""
def write(self, data):
self.data_written += data
class MockSerialPortDataReader(object):
def __init__(self, data=None):
self.data_read = ""
self._expected_data = None
self._set_expected_data(data or "")
def read(self, size):
chunk = "".join(islice(self._expected_data, size))
self.data_read += chunk
return chunk
def _set_expected_data(self, data):
if ">" not in data:
data += ">"
self._expected_data = iter(data)
self.data_read = ""
| {
"repo_name": "franciscoruiz/python-elm",
"path": "tests/utils.py",
"copies": "1",
"size": "4509",
"license": "mit",
"hash": -2164039503823307500,
"line_mean": 26.1626506024,
"line_max": 80,
"alpha_frac": 0.5169660679,
"autogenerated": false,
"ratio": 4.237781954887218,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00007437156031533541,
"num_lines": 166
} |
from functools import wraps
from itertools import izip
from inspect import getargspec
from collections import Callable
def async(func):
""" Decorator to turn a generator function into an asynchronous function,
with yield points corresponding to asynchronous waits (they're also used
to convey how asynchronous callbacks should be used)::
>>> from threading import Thread
>>> from time import sleep
>>>
>>> def timeout(func, interval):
... def target(): sleep(interval); func()
... Thread(target=target).start()
...
>>> @async
... def do_stuff(callback):
... ret = yield timeout((yield lambda: 'something'), 1)
... print ret
... callback('done!')
...
>>> import sys
>>>
>>> @async
... def more_stuff(num, callback=lambda: sys.stdout.write('all done!\\n')):
... print 'starting', num
... print (yield do_stuff((yield lambda ret: ret)))
...
>>> more_stuff(4)
starting 4
>>> sleep(2)
something
done!
all done!
The wrapped function must accept a parameter by the *exact* name of
"callback", which is the sole exit point after all asynchronous execution
of the function completes. To indicate where the callbacks of asynchronous
functions that are called go and behave, yield a lambda in their place.
This lambda will be called with the arguments to that asynchronous callback
and the result will be what is returned from the surrounding yield point.
If by your function never calls its ``callback``, it will be called after it
exits, with no parameters. So for instance, if you need to "return" values to
the callback, you will need to call it yourself, with whatever, at the end
of your function.
"""
argspec = getargspec(func)
args = argspec.args
if not 'callback' in args:
raise ValueError('function does not have a "callback" argument')
cbidx = args.index('callback')
cbdflt = argspec.defaults and \
next((v for k,v in izip(reversed(args), reversed(argspec.defaults))
if k == 'callback'), None)
@wraps(func)
def ret(*args, **kwargs):
# locate and extract callback
if cbidx < len(args):
args = list(args)
callback = args.pop(cbidx)
else:
callback = kwargs.get('callback', cbdflt)
# wrap our callback
did_call_cb_ref = [False]
def complete(*args, **kwargs):
did_call_cb_ref[0] = True
callback(*args, **kwargs)
kwargs['callback'] = complete
gen = func(*args, **kwargs)
def step(val):
try: cont = gen.send(val)
except StopIteration:
if not did_call_cb_ref[0]: callback()
return
# the generator sends continuation points, expecting callbacks provided
# to asynchronous procedure calls
if isinstance(cont, Callable):
step(lambda *args, **kwargs: step(cont(*args, **kwargs)))
step(None)
return ret
| {
"repo_name": "ejones/home",
"path": "misc_py/async.py",
"copies": "1",
"size": "3143",
"license": "mit",
"hash": 5399555722398393000,
"line_mean": 33.1630434783,
"line_max": 84,
"alpha_frac": 0.6048361438,
"autogenerated": false,
"ratio": 4.496423462088698,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5601259605888698,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from itertools import starmap
__ALL__ = ['overload']
def check_arg(arg, spec):
if isinstance(spec, (type, tuple)):
return isinstance(arg, spec)
elif callable(spec):
return spec(arg)
else:
raise TypeError('Unknown argument spec %s' % repr(spec))
def check_spec(types, args):
return len(types) == len(args) and all(starmap(check_arg, zip(args, types)))
def select_overloaded(func, args):
for ts, f in func.overload:
if check_spec(ts, args):
return f
else:
argtypes = ', '.join(type(a).__name__ for a in args)
raise TypeError('No overloaded version of %s() matching %s argument type(s)'
% (func.__name__, argtypes))
def overload(*types):
def decorator(func):
func.overload = getattr(func.__globals__.get(func.__name__), 'overload', [])
func.overload.append((types, func))
def wrapper(*args):
return select_overloaded(func, args)(*args)
return wraps(func)(wrapper)
return decorator
| {
"repo_name": "Suor/overload",
"path": "overload.py",
"copies": "1",
"size": "1077",
"license": "bsd-3-clause",
"hash": 1412974018618756900,
"line_mean": 29.7714285714,
"line_max": 84,
"alpha_frac": 0.6035283194,
"autogenerated": false,
"ratio": 3.7922535211267605,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48957818405267606,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from json import dumps
from typing import Any, Callable, Collection, Optional
from ..language.ast import Node, OperationType
from .visitor import visit, Visitor
from .block_string import print_block_string
__all__ = ["print_ast"]
MAX_LINE_LENGTH = 80
Strings = Collection[str]
class PrintedNode:
"""A union type for all nodes that have been processed by the printer."""
alias: str
arguments: Strings
block: bool
default_value: str
definitions: Strings
description: str
directives: str
fields: Strings
interfaces: Strings
locations: Strings
name: str
operation: OperationType
operation_types: Strings
repeatable: bool
selection_set: str
selections: Strings
type: str
type_condition: str
types: Strings
value: str
values: Strings
variable: str
variable_definitions: Strings
def print_ast(ast: Node) -> str:
"""Convert an AST into a string.
The conversion is done using a set of reasonable formatting rules.
"""
return visit(ast, PrintAstVisitor())
def add_description(method: Callable[..., str]) -> Callable:
"""Decorator adding the description to the output of a static visitor method."""
@wraps(method)
def wrapped(node: PrintedNode, *args: Any) -> str:
return join((node.description, method(node, *args)), "\n")
return wrapped
class PrintAstVisitor(Visitor):
@staticmethod
def leave_name(node: PrintedNode, *_args: Any) -> str:
return node.value
@staticmethod
def leave_variable(node: PrintedNode, *_args: Any) -> str:
return f"${node.name}"
# Document
@staticmethod
def leave_document(node: PrintedNode, *_args: Any) -> str:
return join(node.definitions, "\n\n") + "\n"
@staticmethod
def leave_operation_definition(node: PrintedNode, *_args: Any) -> str:
name, op, selection_set = node.name, node.operation, node.selection_set
var_defs = wrap("(", join(node.variable_definitions, ", "), ")")
directives = join(node.directives, " ")
# Anonymous queries with no directives or variable definitions can use the
# query short form.
return (
join((op.value, join((name, var_defs)), directives, selection_set), " ")
if (name or directives or var_defs or op != OperationType.QUERY)
else selection_set
)
@staticmethod
def leave_variable_definition(node: PrintedNode, *_args: Any) -> str:
return (
f"{node.variable}: {node.type}"
f"{wrap(' = ', node.default_value)}"
f"{wrap(' ', join(node.directives, ' '))}"
)
@staticmethod
def leave_selection_set(node: PrintedNode, *_args: Any) -> str:
return block(node.selections)
@staticmethod
def leave_field(node: PrintedNode, *_args: Any) -> str:
prefix = wrap("", node.alias, ": ") + node.name
args_line = prefix + wrap("(", join(node.arguments, ", "), ")")
if len(args_line) > MAX_LINE_LENGTH:
args_line = prefix + wrap("(\n", indent(join(node.arguments, "\n")), "\n)")
return join((args_line, join(node.directives, " "), node.selection_set), " ")
@staticmethod
def leave_argument(node: PrintedNode, *_args: Any) -> str:
return f"{node.name}: {node.value}"
# Fragments
@staticmethod
def leave_fragment_spread(node: PrintedNode, *_args: Any) -> str:
return f"...{node.name}{wrap(' ', join(node.directives, ' '))}"
@staticmethod
def leave_inline_fragment(node: PrintedNode, *_args: Any) -> str:
return join(
(
"...",
wrap("on ", node.type_condition),
join(node.directives, " "),
node.selection_set,
),
" ",
)
@staticmethod
def leave_fragment_definition(node: PrintedNode, *_args: Any) -> str:
# Note: fragment variable definitions are experimental and may be changed or
# removed in the future.
return (
f"fragment {node.name}"
f"{wrap('(', join(node.variable_definitions, ', '), ')')}"
f" on {node.type_condition}"
f" {wrap('', join(node.directives, ' '), ' ')}"
f"{node.selection_set}"
)
# Value
@staticmethod
def leave_int_value(node: PrintedNode, *_args: Any) -> str:
return node.value
@staticmethod
def leave_float_value(node: PrintedNode, *_args: Any) -> str:
return node.value
@staticmethod
def leave_string_value(node: PrintedNode, key: str, *_args: Any) -> str:
if node.block:
return print_block_string(node.value, "" if key == "description" else " ")
return dumps(node.value)
@staticmethod
def leave_boolean_value(node: PrintedNode, *_args: Any) -> str:
return "true" if node.value else "false"
@staticmethod
def leave_null_value(_node: PrintedNode, *_args: Any) -> str:
return "null"
@staticmethod
def leave_enum_value(node: PrintedNode, *_args: Any) -> str:
return node.value
@staticmethod
def leave_list_value(node: PrintedNode, *_args: Any) -> str:
return f"[{join(node.values, ', ')}]"
@staticmethod
def leave_object_value(node: PrintedNode, *_args: Any) -> str:
return f"{{{join(node.fields, ', ')}}}"
@staticmethod
def leave_object_field(node: PrintedNode, *_args: Any) -> str:
return f"{node.name}: {node.value}"
# Directive
@staticmethod
def leave_directive(node: PrintedNode, *_args: Any) -> str:
return f"@{node.name}{wrap('(', join(node.arguments, ', '), ')')}"
# Type
@staticmethod
def leave_named_type(node: PrintedNode, *_args: Any) -> str:
return node.name
@staticmethod
def leave_list_type(node: PrintedNode, *_args: Any) -> str:
return f"[{node.type}]"
@staticmethod
def leave_non_null_type(node: PrintedNode, *_args: Any) -> str:
return f"{node.type}!"
# Type System Definitions
@staticmethod
@add_description
def leave_schema_definition(node: PrintedNode, *_args: Any) -> str:
return join(
("schema", join(node.directives, " "), block(node.operation_types)), " "
)
@staticmethod
def leave_operation_type_definition(node: PrintedNode, *_args: Any) -> str:
return f"{node.operation.value}: {node.type}"
@staticmethod
@add_description
def leave_scalar_type_definition(node: PrintedNode, *_args: Any) -> str:
return join(("scalar", node.name, join(node.directives, " ")), " ")
@staticmethod
@add_description
def leave_object_type_definition(node: PrintedNode, *_args: Any) -> str:
return join(
(
"type",
node.name,
wrap("implements ", join(node.interfaces, " & ")),
join(node.directives, " "),
block(node.fields),
),
" ",
)
@staticmethod
@add_description
def leave_field_definition(node: PrintedNode, *_args: Any) -> str:
args = node.arguments
args = (
wrap("(\n", indent(join(args, "\n")), "\n)")
if has_multiline_items(args)
else wrap("(", join(args, ", "), ")")
)
directives = wrap(" ", join(node.directives, " "))
return f"{node.name}{args}: {node.type}{directives}"
@staticmethod
@add_description
def leave_input_value_definition(node: PrintedNode, *_args: Any) -> str:
return join(
(
f"{node.name}: {node.type}",
wrap("= ", node.default_value),
join(node.directives, " "),
),
" ",
)
@staticmethod
@add_description
def leave_interface_type_definition(node: PrintedNode, *_args: Any) -> str:
return join(
(
"interface",
node.name,
wrap("implements ", join(node.interfaces, " & ")),
join(node.directives, " "),
block(node.fields),
),
" ",
)
@staticmethod
@add_description
def leave_union_type_definition(node: PrintedNode, *_args: Any) -> str:
return join(
(
"union",
node.name,
join(node.directives, " "),
"= " + join(node.types, " | ") if node.types else "",
),
" ",
)
@staticmethod
@add_description
def leave_enum_type_definition(node: PrintedNode, *_args: Any) -> str:
return join(
("enum", node.name, join(node.directives, " "), block(node.values)), " "
)
@staticmethod
@add_description
def leave_enum_value_definition(node: PrintedNode, *_args: Any) -> str:
return join((node.name, join(node.directives, " ")), " ")
@staticmethod
@add_description
def leave_input_object_type_definition(node: PrintedNode, *_args: Any) -> str:
return join(
("input", node.name, join(node.directives, " "), block(node.fields)), " "
)
@staticmethod
@add_description
def leave_directive_definition(node: PrintedNode, *_args: Any) -> str:
args = node.arguments
args = (
wrap("(\n", indent(join(args, "\n")), "\n)")
if has_multiline_items(args)
else wrap("(", join(args, ", "), ")")
)
repeatable = " repeatable" if node.repeatable else ""
locations = join(node.locations, " | ")
return f"directive @{node.name}{args}{repeatable} on {locations}"
@staticmethod
def leave_schema_extension(node: PrintedNode, *_args: Any) -> str:
return join(
("extend schema", join(node.directives, " "), block(node.operation_types)),
" ",
)
@staticmethod
def leave_scalar_type_extension(node: PrintedNode, *_args: Any) -> str:
return join(("extend scalar", node.name, join(node.directives, " ")), " ")
@staticmethod
def leave_object_type_extension(node: PrintedNode, *_args: Any) -> str:
return join(
(
"extend type",
node.name,
wrap("implements ", join(node.interfaces, " & ")),
join(node.directives, " "),
block(node.fields),
),
" ",
)
@staticmethod
def leave_interface_type_extension(node: PrintedNode, *_args: Any) -> str:
return join(
(
"extend interface",
node.name,
wrap("implements ", join(node.interfaces, " & ")),
join(node.directives, " "),
block(node.fields),
),
" ",
)
@staticmethod
def leave_union_type_extension(node: PrintedNode, *_args: Any) -> str:
return join(
(
"extend union",
node.name,
join(node.directives, " "),
"= " + join(node.types, " | ") if node.types else "",
),
" ",
)
@staticmethod
def leave_enum_type_extension(node: PrintedNode, *_args: Any) -> str:
return join(
("extend enum", node.name, join(node.directives, " "), block(node.values)),
" ",
)
@staticmethod
def leave_input_object_type_extension(node: PrintedNode, *_args: Any) -> str:
return join(
("extend input", node.name, join(node.directives, " "), block(node.fields)),
" ",
)
def join(strings: Optional[Strings], separator: str = "") -> str:
"""Join strings in a given collection.
Return an empty string if it is None or empty, otherwise join all items together
separated by separator if provided.
"""
return separator.join(s for s in strings if s) if strings else ""
def block(strings: Optional[Strings]) -> str:
"""Return strings inside a block.
Given a collection of strings, return a string with each item on its own line,
wrapped in an indented "{ }" block.
"""
return wrap("{\n", indent(join(strings, "\n")), "\n}")
def wrap(start: str, string: Optional[str], end: str = "") -> str:
"""Wrap string inside other strings at start and end.
If the string is not None or empty, then wrap with start and end, otherwise return
an empty string.
"""
return f"{start}{string}{end}" if string else ""
def indent(string: str) -> str:
"""Indent string with two spaces.
If the string is not None or empty, add two spaces at the beginning of every line
inside the string.
"""
return wrap(" ", string.replace("\n", "\n "))
def is_multiline(string: str) -> bool:
"""Check whether a string consists of multiple lines."""
return "\n" in string
def has_multiline_items(strings: Optional[Strings]) -> bool:
"""Check whether one of the items in the list has multiple lines."""
return any(is_multiline(item) for item in strings) if strings else False
| {
"repo_name": "graphql-python/graphql-core",
"path": "src/graphql/language/printer.py",
"copies": "1",
"size": "13238",
"license": "mit",
"hash": -8872858023667285000,
"line_mean": 29.8578088578,
"line_max": 88,
"alpha_frac": 0.5644357154,
"autogenerated": false,
"ratio": 3.9682254196642686,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005455585143221341,
"num_lines": 429
} |
from functools import wraps
from json import JSONDecodeError
from uuid import UUID
from cerberus import Validator
from trellio import HTTPService, TCPService, HTTPView, TCPView
from .helpers import json_response
class TrellioValidator(Validator):
def _validate_type_uuid(self, value):
try:
UUID(value, version=4)
except ValueError:
return False
return True
def validate_schema(schema=None, allow_unknown=False):
def decorator(func):
@wraps(func)
async def wrapper(self, *args, **kwargs):
if schema:
v = TrellioValidator(schema, allow_unknown=allow_unknown)
if isinstance(self, HTTPService) or isinstance(self, HTTPView):
request = args[0]
try:
payload = await request.json()
except JSONDecodeError:
data = await request.text()
return json_response({'error': 'invalid json', 'data': data}, status=400)
if not v.validate(payload):
return json_response({'error': v.errors}, status=400)
elif isinstance(self, TCPService) or isinstance(self, TCPView):
if not v.validate(kwargs):
return {'error': v.errors}
return await func(self, *args, **kwargs)
return wrapper
return decorator
def required_params(*params):
def decorator(func):
@wraps(func)
async def wrapper(self, *args, **kwargs):
if isinstance(self, HTTPService) or isinstance(self, HTTPView):
request = args[0]
try:
payload = await request.json()
except JSONDecodeError:
data = await request.text()
return json_response({'error': 'invalid json', 'data': data}, status=400)
missing_params = list(filter(lambda x: x not in payload.keys(), params))
if missing_params:
return json_response({'error': 'required params - {} not found'.format(', '.join(missing_params))})
elif isinstance(self, TCPService) or isinstance(self, TCPView):
missing_params = list(filter(lambda x: x not in kwargs.keys(), params))
if missing_params:
return {'error': 'required params - {} not found'.format(', '.join(missing_params))}
return await func(self, *args, **kwargs)
return wrapper
return decorator
| {
"repo_name": "artificilabs/trelliolibs",
"path": "trelliolibs/utils/decorators.py",
"copies": "1",
"size": "2599",
"license": "mit",
"hash": -370061084563326200,
"line_mean": 36.6666666667,
"line_max": 119,
"alpha_frac": 0.561754521,
"autogenerated": false,
"ratio": 4.725454545454546,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0008883929533616301,
"num_lines": 69
} |
from functools import wraps
from jwt.exceptions import InvalidIssuerError, InvalidTokenError
from .asap import _process_asap_token, _verify_issuers
from .utils import SettingsDict
def _with_asap(func=None, backend=None, issuers=None, required=True,
subject_should_match_issuer=None):
if backend is None:
raise ValueError(
'Invalid value for backend. Use a subclass instead.'
)
def with_asap_decorator(func):
@wraps(func)
def with_asap_wrapper(*args, **kwargs):
settings = _update_settings_from_kwargs(
backend.settings,
issuers=issuers, required=required,
subject_should_match_issuer=subject_should_match_issuer
)
request = None
if len(args) > 0:
request = args[0]
error_response = _process_asap_token(
request, backend, settings
)
if error_response is not None:
return error_response
return func(*args, **kwargs)
return with_asap_wrapper
if callable(func):
return with_asap_decorator(func)
return with_asap_decorator
def _restrict_asap(func=None, backend=None, issuers=None,
required=True, subject_should_match_issuer=None):
"""Decorator to allow endpoint-specific ASAP authorization, assuming ASAP
authentication has already occurred.
"""
def restrict_asap_decorator(func):
@wraps(func)
def restrict_asap_wrapper(request, *args, **kwargs):
settings = _update_settings_from_kwargs(
backend.settings,
issuers=issuers, required=required,
subject_should_match_issuer=subject_should_match_issuer
)
asap_claims = getattr(request, 'asap_claims', None)
error_response = None
if required and not asap_claims:
return backend.get_401_response(
'Unauthorized', request=request
)
try:
_verify_issuers(asap_claims, settings.ASAP_VALID_ISSUERS)
except InvalidIssuerError:
error_response = backend.get_403_response(
'Forbidden: Invalid token issuer', request=request
)
except InvalidTokenError:
error_response = backend.get_401_response(
'Unauthorized: Invalid token', request=request
)
if error_response and required:
return error_response
return func(request, *args, **kwargs)
return restrict_asap_wrapper
if callable(func):
return restrict_asap_decorator(func)
return restrict_asap_decorator
def _update_settings_from_kwargs(settings, issuers=None, required=True,
subject_should_match_issuer=None):
settings = settings.copy()
if issuers is not None:
settings['ASAP_VALID_ISSUERS'] = set(issuers)
if required is not None:
settings['ASAP_REQUIRED'] = required
if subject_should_match_issuer is not None:
settings['ASAP_SUBJECT_SHOULD_MATCH_ISSUER'] = (
subject_should_match_issuer
)
return SettingsDict(settings)
| {
"repo_name": "atlassian/asap-authentication-python",
"path": "atlassian_jwt_auth/frameworks/common/decorators.py",
"copies": "1",
"size": "3338",
"license": "mit",
"hash": 9004969093819916000,
"line_mean": 30.4905660377,
"line_max": 77,
"alpha_frac": 0.5913720791,
"autogenerated": false,
"ratio": 4.307096774193548,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 106
} |
from functools import wraps
from limits.util import parse, parse_many
from .util import LimitWrapper
DECORATED = {}
EXEMPT = []
def limit(limit_value, key_function=None, per_method=False):
"""
decorator to be used for rate limiting individual views
:param limit_value: rate limit string or a callable that returns a string.
:ref:`ratelimit-string` for more details.
:param function key_func: function/lambda to extract the unique identifier for
the rate limit. defaults to remote address of the request.
:param bool per_method: whether the limit is sub categorized into the http
method of the request.
"""
def __inner(fn):
@wraps(fn)
def _inner(*args, **kwargs):
return fn(*args, **kwargs)
if fn in DECORATED:
DECORATED.setdefault(_inner, DECORATED.pop(fn))
if callable(limit_value):
DECORATED.setdefault(_inner, []).append(
LimitWrapper(limit_value, key_function, None, per_method)
)
else:
DECORATED.setdefault(_inner, []).extend([
LimitWrapper(
list(parse_many(limit_value)), key_function, None, per_method
)
])
return _inner
return __inner
def shared_limit(limit_value, scope, key_function=None):
"""
decorator to be applied to multiple views sharing the same rate limit.
:param limit_value: rate limit string or a callable that returns a string.
:ref:`ratelimit-string` for more details.
:param scope: a string or callable that returns a string
for defining the rate limiting scope.
:param function key_func: function/lambda to extract the unique identifier for
the rate limit. defaults to remote address of the request.
"""
def __inner(fn):
@wraps(fn)
def _inner(*args, **kwargs):
return fn(*args, **kwargs)
if fn in DECORATED:
DECORATED.setdefault(_inner, DECORATED.pop(fn))
if callable(limit_value):
DECORATED.setdefault(_inner, []).append(
LimitWrapper(limit_value, key_function, scope)
)
else:
DECORATED.setdefault(_inner, []).extend([
LimitWrapper(
list(parse_many(limit_value)), key_function, scope
)
])
return _inner
return __inner
def exempt(fn):
"""
decorator to mark a view or all views in a blueprint as exempt from rate limits.
:param fn: the view to wrap.
:return:
"""
@wraps(fn)
def __inner(*a, **k):
return fn(*a, **k)
EXEMPT.append(__inner)
return __inner
| {
"repo_name": "alisaifee/djlimiter",
"path": "djlimiter/decorators.py",
"copies": "1",
"size": "2702",
"license": "mit",
"hash": -9078779551613909000,
"line_mean": 31.5542168675,
"line_max": 84,
"alpha_frac": 0.6028867506,
"autogenerated": false,
"ratio": 4.169753086419753,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5272639837019752,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from locale import setlocale
from django.db.models.signals import (
post_delete,
post_init,
post_save,
pre_delete,
pre_init,
pre_save,
)
def signal_connect(cls):
"""
Class decorator that automatically connects pre_save / post_save signals on
a model class to its pre_save() / post_save() methods.
"""
def connect(signal, func):
cls.func = staticmethod(func)
@wraps(func)
def wrapper(sender, *args, **kwargs):
return func(kwargs.get('instance'), *args, **kwargs)
signal.connect(wrapper, sender=cls)
return wrapper
if hasattr(cls, 'post_delete'):
cls.post_delete = connect(post_delete, cls.post_delete)
if hasattr(cls, 'post_init'):
cls.post_init = connect(post_init, cls.post_init)
if hasattr(cls, 'post_save'):
cls.post_save = connect(post_save, cls.post_save)
if hasattr(cls, 'pre_delete'):
cls.pre_delete = connect(pre_delete, cls.pre_delete)
if hasattr(cls, 'pre_init'):
cls.pre_init = connect(pre_init, cls.pre_init)
if hasattr(cls, 'pre_save'):
cls.pre_save = connect(pre_save, cls.pre_save)
return cls
def signal_skip(func):
@wraps(func)
def _decorator(sender, instance, **kwargs):
if hasattr(instance, 'skip_signal'):
return None
instance.skip_signal = True
return func(sender, instance, **kwargs)
return _decorator
def locale(cat, loc):
def _decorator(func):
@wraps(func)
def _wrapper(*args, **kwargs):
orig = setlocale(cat, loc)
value = func(*args, **kwargs)
setlocale(cat, orig)
return value
return _wrapper
return _decorator
def docstring_format(*args, **kwargs):
def _decorator(obj):
if getattr(obj, '__doc__', None):
obj.__doc__ = obj.__doc__.format(*args, **kwargs)
return obj
return _decorator
| {
"repo_name": "medunigraz/outpost",
"path": "src/outpost/django/base/decorators.py",
"copies": "1",
"size": "1991",
"license": "bsd-2-clause",
"hash": -3762769164526640000,
"line_mean": 24.8571428571,
"line_max": 79,
"alpha_frac": 0.5976896032,
"autogenerated": false,
"ratio": 3.700743494423792,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47984330976237916,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from logging import getLogger
from shutil import move, copy
from core.exceptions import RestoreError
from core.tokenizer import Tokenizer
from os.path import join, basename, isfile, expanduser
from settings.settings import CONFIG_FILES, REPO_PATH, FILE_NAME_TO_COMMIT
from utils.helpers import get_json_config, extract_files
log = getLogger("Restore")
def exception_decorator(func):
@wraps(func)
def func_wrapper(*args, **kw):
try:
return func(*args, **kw)
except Exception as e:
log.error("Restore process failed: {}".format(e))
raise RestoreError(message=e)
return func_wrapper
class Restore(object):
def __init__(self, remote_procedure):
self.remote_procedure = remote_procedure
try:
self.configs = get_json_config('{}'.format(CONFIG_FILES))
except IOError as e:
log.error("could not load json. Please check config file")
raise e
@exception_decorator
def restore(self):
log.info("Restoring...")
self.remote_procedure.remote.fetch_from_remote()
extract_files(
to_extract=join(REPO_PATH, FILE_NAME_TO_COMMIT),
save_to_folder=join(REPO_PATH, FILE_NAME_TO_COMMIT)
)
for config_file in self.configs:
config_path = expanduser(join('~/', config_file.get('config_path')))
restore_path = join(
REPO_PATH,
FILE_NAME_TO_COMMIT,
basename(config_path)
)
if isfile(restore_path):
self.restore_file(
config_path, restore_path, config_file.get('tokenize')
)
def restore_file(self, dest_path, tokenized_path, token_list):
if not isfile(dest_path):
move(tokenized_path, dest_path)
else:
log.info(
"Restoring file at {0}, from {1} with tokens {2}".format(
dest_path, tokenized_path, token_list
)
)
Tokenizer().replace_tokens_with_actual(
dest_path, tokenized_path, token_list
)
log.info("Moving {0} to {1}".format(tokenized_path, dest_path))
move(src=tokenized_path, dst=dest_path)
| {
"repo_name": "idjaw/dot-manager",
"path": "app/core/restore.py",
"copies": "1",
"size": "2325",
"license": "mit",
"hash": -3439930974100434000,
"line_mean": 32.2142857143,
"line_max": 80,
"alpha_frac": 0.5853763441,
"autogenerated": false,
"ratio": 4.09330985915493,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00017636684303350968,
"num_lines": 70
} |
from functools import wraps
from logging import getLogger
from mongosql import CrudViewMixin, StrictCrudHelper, StrictCrudHelperSettingsDict, saves_relations
from . import models
from flask import request, g, jsonify
from flask_jsontools import jsonapi, RestfulView
logger = getLogger(__name__)
def passthrough_decorator(f):
""" A no-op decorator.
It's only purpose is to see whether @saves_relations() works even when decorated with something else.
"""
@wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
return wrapper
class RestfulModelView(RestfulView, CrudViewMixin):
""" Base view class for all other views """
crudhelper = None
# RestfulView needs that for routing
primary_key = None
decorators = (jsonapi,)
# Every response will have either { article: ... } or { articles: [...] }
# Stick to the DRY principle: store the key name once
entity_name = None
entity_names = None
# Implement the method that fetches the Query Object for this request
def _get_query_object(self):
""" Get Query Object from request
:rtype: dict | None
"""
return (request.get_json() or {}).get('query', None)
# CrudViewMixin demands: needs to be able to get a session so that it can run a query
def _get_db_session(self):
""" Get database Session
:rtype: sqlalchemy.orm.Session
"""
return g.db
# This is our method: it plucks an instance using the current projection
# This is just convenience: if the user has requested
def _return_instance(self, instance):
""" Modify a returned instance """
return self._mongoquery.pluck_instance(instance)
def _save_hook(self, new: models.Article, prev: models.Article = None):
# There's one special case for a failure: title='z'.
# This is how unit-tests can test exceptions
if new.title == 'z':
# Simulate a bug
raise RuntimeError(
'This method inexplicably fails when title="z"'
)
super()._save_hook(new, prev)
# region CRUD methods
def list(self):
""" List method: GET /article/ """
# List results
results = self._method_list()
# Format response
# NOTE: can't return map(), because it's not JSON serializable
return {self.entity_names: results}
def _method_list_result__groups(self, dicts):
""" Format the result from GET /article/ when the result is a list of dicts (GROUP BY) """
return list(dicts) # our JSON serializer does not like generators. Have to make it into a list
def _method_list_result__entities(self, entities):
""" Format the result from GET /article/ when the result is a list of sqlalchemy entities """
# Pluck results: apply projection to the result set
# This is just our good manners: if the client has requested certain fields, we return only those they requested.
# Even if our code loads some more columns (and it does!), the client will always get what they requested.
return list(map(self._return_instance, entities))
def get(self, id):
item = self._method_get(id=id)
return {self.entity_name: self._return_instance(item)}
def create(self):
# Trying to save many objects at once?
if self.entity_names in request.get_json():
return self.save_many()
# Saving only one object
input_entity_dict = request.get_json()[self.entity_name]
instance = self._method_create(input_entity_dict)
ssn = self._get_db_session()
ssn.add(instance)
ssn.commit()
return {self.entity_name: self._return_instance(instance)}
def save_many(self):
# Get the input
input_json = request.get_json()
entity_dicts = input_json[self.entity_names]
# Process
results = self._method_create_or_update_many(entity_dicts)
# Save
ssn = self._get_db_session()
ssn.add_all(res.instance for res in results if res.instance is not None)
ssn.commit()
# Log every error
for res in results:
if res.error:
logger.exception(str(res.error), exc_info=res.error)
# Results
return {
# Entities
self.entity_names: [
# Each one goes through self._return_instance()
self._return_instance(res.instance) if res.instance else None
for res in results
],
# Errors
'errors': {
res.ordinal_number: str(res.error)
for res in results
if res.error
},
}
def update(self, id):
input_entity_dict = request.get_json()[self.entity_name]
instance = self._method_update(input_entity_dict, id=id)
ssn = self._get_db_session()
ssn.add(instance)
ssn.commit()
return {self.entity_name: self._return_instance(instance)}
def delete(self, id):
instance = self._method_delete(id=id)
ssn = self._get_db_session()
ssn.delete(instance)
ssn.commit()
return {self.entity_name: self._return_instance(instance)}
# endregion
class ArticleView(RestfulModelView):
""" Full-featured CRUD view """
# First, configure a CrudHelper
crudhelper = StrictCrudHelper(
# The model to work with
models.Article,
**StrictCrudHelperSettingsDict(
# Read-only fields, as a callable (just because)
ro_fields=lambda: ('id', 'uid',),
legacy_fields=('removed_column',),
# MongoQuery settings
aggregate_columns=('id', 'data',), # have to explicitly enable aggregation for columns
query_defaults=dict(
sort=('id-',),
),
writable_properties=True,
max_items=2,
# Related entities configuration
allowed_relations=('user', 'comments'),
related={
'user': dict(
# Exclude @property by default
default_exclude=('user_calculated',),
allowed_relations=('comments',),
related={
'comments': dict(
# Exclude @property by default
default_exclude=('comment_calc',),
# No further joins
join_enabled=False,
)
}
),
'comments': dict(
# Exclude @property by default
default_exclude=('comment_calc',),
# No further joins
join_enabled=False,
),
},
)
)
# ensure_loaded: always load these columns and relationships
# This is necessary in case some custom code relies on it
ensure_loaded = ('data', 'comments') # that's a weird requirement, but since the user is supposed to use projections, it will be excluded
primary_key = ('id',)
decorators = (jsonapi,)
entity_name = 'article'
entity_names = 'articles'
def _method_create(self, entity_dict: dict) -> object:
instance = super()._method_create(entity_dict)
instance.uid = 3 # Manually set ro field value, because the client can't
return instance
# Our completely custom stuff
@passthrough_decorator # no-op to demonstrate that it still works
@saves_relations('comments')
def save_comments(self, new, prev=None, comments=None):
# Just store it in the class for unit-test to find it
self.__class__._save_comments__args = dict(new=new, prev=prev, comments=comments)
@passthrough_decorator # no-op to demonstrate that it still works
@saves_relations('user', 'comments')
def save_relations(self, new, prev=None, user=None, comments=None):
# Just store it in the class for unit-test to find it
self.__class__._save_relations__args = dict(new=new, prev=prev, user=user, comments=comments)
@saves_relations('removed_column')
def save_removed_column(self, new, prev=None, removed_column=None):
# Store
self.__class__._save_removed_column = dict(removed_column=removed_column)
_save_comments__args = None
_save_relations__args = None
_save_removed_column = None
class GirlWatcherView(RestfulModelView):
crudhelper = StrictCrudHelper(
models.GirlWatcher,
**StrictCrudHelperSettingsDict(
# Read-only fields, as a callable (just because)
ro_fields=('id', 'favorite_id',),
allowed_relations=('good', 'best')
)
)
primary_key = ('id',)
decorators = (jsonapi,)
entity_name = 'girlwatcher'
entity_names = 'girlwatchers'
def _return_instance(self, instance):
instance = super()._return_instance(instance)
# TypeError: Object of type _AssociationList is not JSON serializable
for k in ('good_names', 'best_names'):
if k in instance:
# Convert this _AssociationList() object into a real list
instance[k] = list(instance[k])
return instance
| {
"repo_name": "kolypto/py-mongosql",
"path": "tests/crud_view.py",
"copies": "1",
"size": "9409",
"license": "bsd-2-clause",
"hash": 6901548853220053000,
"line_mean": 33.3394160584,
"line_max": 142,
"alpha_frac": 0.5928366458,
"autogenerated": false,
"ratio": 4.269056261343013,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5361892907143012,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from logging import getLogger
logger = getLogger(__name__)
def set_parameter(function):
@wraps(function)
def _set_parameter(self, name, value, **kwargs):
if name not in self.parameters.index:
logger.error("Parameter name {} does not exist, please choose "
"from {}".format(name, self.parameters.index))
else:
return function(self, name, value, **kwargs)
return _set_parameter
def get_stressmodel(function):
@wraps(function)
def _get_stressmodel(self, name, **kwargs):
if name not in self.stressmodels.keys():
logger.error("The stressmodel name you provided is not in the "
"stressmodels dict. Please select from the "
"following list: {}".format(self.stressmodels.keys()))
else:
return function(self, name, **kwargs)
return _get_stressmodel
def model_tmin_tmax(function):
@wraps(function)
def _model_tmin_tmax(self, tmin=None, tmax=None, *args, **kwargs):
if tmin is None:
tmin = self.ml.settings["tmin"]
if tmax is None:
tmax = self.ml.settings["tmax"]
return function(self, tmin, tmax, *args, **kwargs)
return _model_tmin_tmax
def PastasDeprecationWarning(function):
@wraps(function)
def _function(*args, **kwargs):
logger.warning("Deprecation warning: method will be deprecated "
"in version 0.14.0.")
return function(*args, **kwargs)
return _function
| {
"repo_name": "gwtsa/gwtsa",
"path": "pastas/decorators.py",
"copies": "1",
"size": "1587",
"license": "mit",
"hash": -652258072991897000,
"line_mean": 29.5192307692,
"line_max": 79,
"alpha_frac": 0.6049149338,
"autogenerated": false,
"ratio": 4.007575757575758,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 52
} |
from functools import wraps
from lxml.etree import ParseError
from requests import RequestException
from _exception import http_404, http_301
def ensure_index(fn):
"""
Decorator for the handle() method of any handler. Ensures that
indexes requested without a trailing slash are redirected to a
version with the trailing slash.
"""
@wraps(fn)
def wrapper(self, path, request, response):
if not request.is_index:
raise http_301((path[-1] + '/') if path else '/')
return fn(self, path, request, response)
return wrapper
def ensure_python_dir(fn):
"""
Decorator for the handle() method of any handler. Ensures that
indexes and files requested are all under the root python/
directory.
"""
@wraps(fn)
def wrapper(self, path, request, response):
if path[0] != 'python':
raise http_404('Not under "python/" directory')
return fn(self, path, request, response)
return wrapper
def fetch_and_parse_index(
http_get_fn,
parse_index_fn,
pypi_base_url,
index_url,
package_path):
try:
index_html_str = http_get_fn(url=index_url)
except RequestException:
raise http_404('Index "{}" cannot be reached'.format(index_url))
try:
index_rows = parse_index_fn(
base_url=pypi_base_url,
package_path=package_path,
html_str=index_html_str)
except ParseError:
raise http_404('Index "{}" failed to be parsed'.format(index_url))
return index_rows
| {
"repo_name": "teamfruit/defend_against_fruit",
"path": "pypi_redirect/pypi_redirect/server_app/handler/_utils.py",
"copies": "1",
"size": "1574",
"license": "apache-2.0",
"hash": 8869946685771187000,
"line_mean": 28.1481481481,
"line_max": 74,
"alpha_frac": 0.6296060991,
"autogenerated": false,
"ratio": 4.01530612244898,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 54
} |
from functools import wraps
from lxml import etree
import logging
from django.http import HttpResponse
logger = logging.getLogger(__name__)
#I only use this decorator with REST calls so if failed I respond with an XML
def http_basic_auth(func):
@wraps(func)
def _decorator(request, *args, **kwargs):
from django.contrib.auth import authenticate, login
if request.META.has_key('HTTP_AUTHORIZATION'):
authmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
if authmeth.lower() == 'basic':
auth = auth.strip().decode('base64')
username, password = auth.split(':', 1)
user = authenticate(username=username, password=password)
if user:
request.user = user
return func(request, *args, **kwargs)
# Either they did not provide an authorization head er or
# something in the authorization attempt failed. Send an XML with
# <root><response>0</response><msg>Basic http authentication failed</msg></root>S
#
#
#XML Response
##############
# create XML 1
root = etree.Element('root')
#root.append(etree.Element('child'))
# another child with text
child = etree.Element('response')
child.text = '0'
root.append(child)
child = etree.Element('msg')
child.text = 'Basic http authentication failed'
root.append(child)
# pretty string
s = etree.tostring(root, pretty_print=True)
logger.debug('0-Basic http authentication failed')
#Before Django 1.7 mimetype was used, take into account for future implementations
return HttpResponse(s, content_type='application/xml')
return _decorator
| {
"repo_name": "Si-elegans/Web-based_GUI_Tools",
"path": "mysite/my_decorators.py",
"copies": "1",
"size": "1842",
"license": "apache-2.0",
"hash": -6688727487614615000,
"line_mean": 39.0434782609,
"line_max": 90,
"alpha_frac": 0.6026058632,
"autogenerated": false,
"ratio": 4.593516209476309,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.569612207267631,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from lxml import html
import json
import logging
import re
import time
import urllib
import urllib2
MAXRETRIES = 3
RETRYSLEEP = 5
class Connection:
def __init__(self, hostname, baseurl, opener, auth_cookies):
self.host = hostname
self.opener = opener
self.auth_cookies = auth_cookies
self.baseurl = baseurl
self.connected = False
def get_ui_return_html_status(conn, path, params):
page, url, http_code = _request(conn, "GET", path, params, [], urllib.urlencode, html.fromstring)
return page, url, http_code
def get_ui_return_html(conn, path, params):
res, _, _ = _request(conn, "GET", path, params, [], urllib.urlencode, html.fromstring)
return res
def get_ui_return_json(conn, path, params):
headers = [('Accept', 'application/json')]
try:
res, _, _ = _request(conn, "GET", path, params, headers, urllib.urlencode, json.loads)
except:
res = {'status':'NotOK'}
return res
def post_ui_no_return(conn, path, params):
res,_ , _ = _request(conn, "POST", path, params, [], urllib.urlencode, id)
def post_ui_return_html(conn, path, params):
res, _, _ = _request(conn, "POST", path, params, [], urllib.urlencode, html.fromstring)
return res
def post_ui_return_json(conn, path, params):
headers = [('Accept', 'application/json')]
try:
res, _, _ = _request(conn, "POST", path, params, headers, urllib.urlencode, json.loads)
except:
res = {'status':'NotOK'}
return res
def get_rest_return_json(conn, path, params):
return get_ui_return_json(conn, path, params)
def post_rest_return_json(conn, path, params):
return get_ui_return_json(conn, path, params)
rolling_avg_counter = 1
rolling_avg_list = []
rolling_avg = 0
def monitoring(func):
@wraps(func)
def with_time_monitoring(*args, **kwargs):
global rolling_avg_counter, rolling_avg_list, rolling_avg
t1 = time.time()
time.sleep(3.0)
t2 = time.time()
logging.debug('slept %(sleep)s seconds.' % {'sleep': (t2 - t1)})
start_time = time.time()
res = func(*args, **kwargs)
end_time = time.time()
logging.debug('%(fname)s took %(dur)s.' % {'fname': func.__name__,
'dur': (end_time - start_time)})
rolling_avg_counter += 1
rolling_avg_list.append(end_time - start_time)
if rolling_avg_counter % 10 == 0:
rolling_avg_counter = 1
rolling_avg = ((rolling_avg + sum(rolling_avg_list)) /
(1 + len(rolling_avg_list)))
rolling_avg_list = []
logging.debug('%(fname)s rolling average is %(dur)s.'
% {'fname': func.__name__,
'dur': rolling_avg})
return res
return with_time_monitoring
@monitoring
def _request(conn, method, path, params, headers, param_parse_func, response_parse_func):
path_and_params = None
if method == "GET":
path_and_params = path+'?'+urllib.urlencode(params) if params else path
else:
path_and_params = path
req = urllib2.Request(conn.host+path_and_params)
for key, value in headers:
req.add_header(key, value)
cookies = []
for c in conn.auth_cookies:
cookies.append(c.name+'='+c.value.strip())
cookies = '; '.join(cookies)
if len(cookies) > 0:
req.add_header('Cookie', cookies)
retries = 0
req_success = False
while not req_success:
logging.debug('%s', req.get_full_url())
try:
if method == "POST":
response = conn.opener.open(req, param_parse_func(params))
elif method == "GET":
response = conn.opener.open(req)
req_success = True
except urllib2.URLError:
if retries >= MAXRETRIES:
raise
time.sleep(RETRYSLEEP)
finally:
retries += 1
logging.debug('%s %s', response.geturl(), response.getcode())
if response.getcode() > 399:
raise urllib2.HTTPError(code=response.getcode())
response_content = response.read()
try:
res = response_parse_func(response_content)
except:
logging.debug('The response content follows:')
logging.debug(response_content)
logging.debug('End of response content.')
raise
return res, response.geturl(), response.getcode()
| {
"repo_name": "mhellmic/bamboo-automate",
"path": "lib/requests.py",
"copies": "1",
"size": "4164",
"license": "apache-2.0",
"hash": 5376310496811034000,
"line_mean": 28.5319148936,
"line_max": 99,
"alpha_frac": 0.636167147,
"autogenerated": false,
"ratio": 3.3853658536585365,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9409116137105575,
"avg_score": 0.022483372710592326,
"num_lines": 141
} |
from functools import wraps
from .main import *
def antibrute_login(func):
"""
Wrapper for login view. This will take care of all the checks and
displaying lockout page
"""
@wraps(func)
def wrap_login(request, *args, **kwargs):
# TODO: IP check goes here here
username = ''
if request.method == 'POST':
username = request.POST.get(FORM_USER_FIELD, '')
if username:
remaining_sec = check_and_update_lock(username)
if remaining_sec:
return get_lockout_response(request, remaining_sec)
# original view
response = func(request, args, kwargs)
# check the result
if request.method == 'POST':
success = (response.status_code and response.has_header('location')
and request.user.is_authenticated)
# add attempt and lock if threshold is reached
process_login_attempt(request, username, success)
return response
return wrap_login
| {
"repo_name": "maulik13/django-antibrute",
"path": "antibrute/decorators.py",
"copies": "1",
"size": "1036",
"license": "mit",
"hash": -6561699092029706000,
"line_mean": 31.375,
"line_max": 79,
"alpha_frac": 0.6013513514,
"autogenerated": false,
"ratio": 4.4655172413793105,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.556686859277931,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from mako.lookup import TemplateLookup
from distill import PY2
import json
from distill.exceptions import HTTPInternalServerError
from distill.response import Response
class RenderFactory(object):
"""
This class provides a wrapper for handling rendering operations
"""
_factory = None
def __init__(self, settings):
""" Init
Args:
settings: The application's settings dict
"""
if PY2: # pragma: no cover
self._template_lookup = TemplateLookup(output_encoding='ascii')
else: # pragma: no cover
self._template_lookup = TemplateLookup(input_encoding='utf-8')
self._template_lookup.directories.append(settings.get('distill.document_root', ''))
self._template_lookup.module_directory = settings.get('distill.document_root', '')
self._renderers = {}
def __call__(self, template, data, request, response, **rkwargs):
""" Actually render the response
Notes:
The current request will be available to template
template as req
Args:
template: The template you're looking up
data: The data to be passed to the template
request: Current request
response: Current response
"""
if '.mako' == template.lower()[-5:]:
if type(data) != dict:
return data
response.headers['Content-Type'] = 'text/html'
data['req'] = request
return self._template_lookup.get_template(template).render(**data)
elif template in self._renderers:
return self._renderers[template](data, request, response, **rkwargs)
raise HTTPInternalServerError(description="Missing template file {0}".format(template))
def register_renderer(self, name, serializer):
"""Adds template to the current instances renderers dict"""
self._renderers[name] = serializer
@staticmethod
def create(settings):
"""Initializes the RenderFactory"""
RenderFactory._factory = RenderFactory(settings)
RenderFactory._factory.register_renderer('json', JSON())
@staticmethod
def render(template, data, request, response, **rkwargs):
"""Returns the rendered response to a template"""
return RenderFactory._factory(template, data, request, response, **rkwargs)
@staticmethod
def add_renderer(name, serializer):
"""Adds a template to the RenderFactory"""
RenderFactory._factory.register_renderer(name, serializer)
def renderer(template, **rkwargs):
""" Decorator for rendering responses
Notes:
When using this decorator the returned value of
on_get or on_post is treated as arguments passed
to the template, as such their meaning will vary
accordingly
"""
def _render(method):
@wraps(method)
def _call(*args, **kwargs):
data = method(*args, **kwargs)
if isinstance(data, Response):
return data
if len(args) == 2:
return RenderFactory.render(template, data, *args, **rkwargs)
else:
return RenderFactory.render(template, data, args[1], args[2], **rkwargs)
return _call
return _render
class JSON(object):
def __init__(self, serializer=json.dumps, **kwargs):
""" Init
Args:
serializer: The serialzer to be used to stringify the object
kwargs: All kwargs will be passed to the serializer
"""
self.serializer = serializer
self.kw = kwargs
def __call__(self, data, request, response, pad=False):
""" Render the response to the template
Notes:
Templates should be callables that accept the
following arguments and return either a string
representing the rendered response body, or a
new response
Args:
data: The data to be rendered
request: The current request, to be used as needed
response: The current response
"""
response.headers['Content-Type'] = 'application/json'
def default(obj):
if hasattr(obj, 'json'):
return obj.json(request)
else:
raise TypeError('%r is not JSON serializable' % obj)
if pad:
return ")]}',\n" + self.serializer(data, default=default, **self.kw)
return self.serializer(data, default=default, **self.kw) | {
"repo_name": "Dreae/Distill",
"path": "distill/renderers.py",
"copies": "1",
"size": "4584",
"license": "mit",
"hash": -4680932281494713000,
"line_mean": 33.7348484848,
"line_max": 95,
"alpha_frac": 0.6106020942,
"autogenerated": false,
"ratio": 4.765072765072765,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007252448322628939,
"num_lines": 132
} |
from functools import wraps
from ..mapping import EpistasisMap
from numpy import random
class DistributionException(Exception):
""""""
class SimulatedEpistasisMap(EpistasisMap):
"""Just like an epistasis map, but with extra methods
for setting epistatic coefficients
"""
def __init__(self, gpm, df=None, sites=None, values=None, stdeviations=None):
super().__init__(df=df, sites=sites, values=values, stdeviations=stdeviations)
self._gpm = gpm
@property
def avail_distributions(self):
return random.__all__
def set_order_from_distribution(self, orders, dist="normal", **kwargs):
"""Sets epistatic coefficients to values drawn from a statistical distribution.
Distributions are found in SciPy's `random` module. Kwargs are passed
directly to these methods
"""
# Get distribution
try:
method = getattr(random, dist)
except AttributeError:
raise DistributionException("Distribution now found. Check the `avail_distribution` "
"attribute for available distributions.")
idx = self.data.orders.isin(orders)
self.data.loc[idx, "values"] = method(
size=sum(idx),
**kwargs
)
self._gpm.build()
@wraps(EpistasisMap.set_values)
def set_values(self, values, filter=None):
super().set_values(values, filter=filter)
self._gpm.build() | {
"repo_name": "harmslab/epistasis",
"path": "epistasis/simulate/mapping.py",
"copies": "2",
"size": "1482",
"license": "unlicense",
"hash": -665115553734013400,
"line_mean": 33.488372093,
"line_max": 97,
"alpha_frac": 0.6322537112,
"autogenerated": false,
"ratio": 4.174647887323943,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.005049688375682592,
"num_lines": 43
} |
from functools import wraps
from math import ceil
from flask import url_for, request, current_app
def _get_page_link(page_number):
return url_for(request.url_rule.endpoint, page=page_number, _external=True)
class PaginationFunctions:
@staticmethod
def paginate(view_function):
@wraps(view_function)
def paginate_function(*args, **kwargs):
if 'page' in request.args:
page = int(request.args['page'])
else:
page = 1
per_page = current_app.config['OBJECTS_PER_PAGE']
queryset = view_function(*args, **kwargs)
page_count = ceil(queryset.count()/per_page)
paginated_queryset = queryset.paginate(page=page, per_page=per_page)
result = {
'results': paginated_queryset.items,
'next': _get_page_link(paginated_queryset.next_num) if paginated_queryset.has_next else None,
'previous': _get_page_link(paginated_queryset.prev_num) if paginated_queryset.has_prev else None,
'page': page,
'page_count': page_count
}
return result
return paginate_function
| {
"repo_name": "mass-project/mass_server",
"path": "mass_flask_core/utils/pagination_functions.py",
"copies": "1",
"size": "1200",
"license": "mit",
"hash": 5713814359072318000,
"line_mean": 37.7096774194,
"line_max": 113,
"alpha_frac": 0.5991666667,
"autogenerated": false,
"ratio": 4.013377926421405,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5112544593121404,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from math import ceil
import numpy as np
import scipy.sparse as sp
def chunks(iterable, chunk_size):
""" Splits iterable objects into chunk of fixed size.
The last chunk may be truncated.
"""
chunk = []
for item in iterable:
chunk.append(item)
if len(chunk) == chunk_size:
yield chunk
chunk = []
if chunk:
yield chunk
def chunkable(method):
""" This decorators wraps methods that can be executed by passing data by chunks.
It allows you to pass additional arguments like `chunk_number` and `on_progress` callback
to monitor the execution's progress.
Note:
If no callback is provided data won't be splitted.
"""
@wraps(method)
def wrapper(self, data, chunk_number=100, on_progress=None, *args, **kwargs):
if on_progress:
chunk_size = ceil(len(data) / chunk_number)
progress = 0
res = []
for i, chunk in enumerate(chunks(data, chunk_size=chunk_size)):
chunk_res = method(self, chunk, *args, **kwargs)
if chunk_res:
res.extend(chunk_res)
progress += len(chunk)
on_progress(progress)
else:
res = method(self, data, *args, **kwargs)
return res
return wrapper
def np_sp_sum(x, axis=None):
""" Wrapper for summing either sparse or dense matrices.
Required since with scipy==0.17.1 np.sum() crashes."""
if sp.issparse(x):
r = x.sum(axis=axis)
if axis is not None:
r = np.array(r).ravel()
return r
else:
return np.sum(x, axis=axis)
| {
"repo_name": "cheral/orange3-text",
"path": "orangecontrib/text/util.py",
"copies": "1",
"size": "1703",
"license": "bsd-2-clause",
"hash": 9068441106863198000,
"line_mean": 26.9180327869,
"line_max": 93,
"alpha_frac": 0.5819142689,
"autogenerated": false,
"ratio": 4.054761904761905,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5136676173661904,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from memsql_framework.util.attr_dict import AttrDict
from memsql_framework.ui import exceptions
ENDPOINTS = {}
def endpoint(name, schema=None, methods=None):
def _deco(wrapped):
@wraps(wrapped)
def _wrap(root, params):
if schema is not None:
params = AttrDict(schema(params))
return wrapped(root, params)
if methods is None:
setattr(_wrap, "__http_methods__", ["POST"])
else:
setattr(_wrap, "__http_methods__", methods)
ENDPOINTS[name] = _wrap
return _wrap
return _deco
def call(root, name, props, method):
endpoint = ENDPOINTS.get(name)
if endpoint is None:
raise exceptions.ApiException("Endpoint not found: %s" % name)
allowed_methods = getattr(endpoint, "__http_methods__")
if method not in allowed_methods:
raise exceptions.ApiException("Method %s not supported by %s" % (method, name))
return endpoint(root, props)
# import all endpoints here
from memsql_framework.ui.api import cluster # noqa
| {
"repo_name": "memsql/memsql-mesos",
"path": "memsql_framework/ui/api/endpoints.py",
"copies": "1",
"size": "1095",
"license": "apache-2.0",
"hash": -3110128063949269500,
"line_mean": 27.8157894737,
"line_max": 87,
"alpha_frac": 0.6365296804,
"autogenerated": false,
"ratio": 3.9388489208633093,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0020762639043714073,
"num_lines": 38
} |
from functools import wraps
from mock import patch
from nose.tools import nottest
from . import (get_all_test_configs, resources_for_test_config, specs_for_test_config,
assembled_specs_for_test_config, nginx_config_for_test_config, docker_compose_yaml_for_test_config)
from dusty.compiler import spec_assembler
from ...testcases import DustyTestCase
from dusty import constants
from dusty.source import Repo
from ..utils import get_app_dusty_schema, get_lib_dusty_schema, get_bundle_dusty_schema, apply_required_keys
@nottest
def all_test_configs(test_func):
@wraps(test_func)
def inner(cls):
for test_config in get_all_test_configs():
case_specs = specs_for_test_config(test_config)
assembled_specs = assembled_specs_for_test_config(test_config)
print "Running test case: {}".format(test_config)
test_func(cls, test_config, case_specs, assembled_specs)
print "Test case {} completed".format(test_config)
return inner
class TestCompilerTestCases(DustyTestCase):
def test_compiler_test_configs(test_config):
for test_config in get_all_test_configs():
pass
class TestSpecAssemblerTestCases(DustyTestCase):
@all_test_configs
def test_retrieves_downstream_apps(self, test_config, case_specs, assembled_specs):
downstream_apps = spec_assembler._get_referenced_apps(case_specs)
assembled_apps = set(assembled_specs['apps'].keys())
self.assertEqual(downstream_apps, assembled_apps)
@all_test_configs
def test_expands_libs_in_apps(self, test_config, case_specs, assembled_specs):
spec_assembler._expand_libs_in_apps(case_specs)
for app_name, app in case_specs['apps'].iteritems():
self.assertEqual(set(app['depends']['libs']), set(assembled_specs['apps'][app_name]['depends']['libs']))
@all_test_configs
def test_assembles_specs(self, test_config, case_specs, assembled_specs, *args):
self.maxDiff = None
bundles = case_specs[constants.CONFIG_BUNDLES_KEY].keys()
@patch('dusty.compiler.spec_assembler._get_active_bundles', return_value=bundles)
def run_patched_assembler(case_specs, *args):
spec_assembler._get_expanded_active_specs(case_specs)
run_patched_assembler(case_specs)
for spec_type in ('bundles', 'apps', 'libs', 'services'):
for name, spec in assembled_specs[spec_type].iteritems():
if spec:
for spec_level_key, value in spec.iteritems():
if spec_type == 'apps' and spec_level_key == 'depends' and value['libs'] == []:
value['libs'] = set([])
self.assertEquals(value, case_specs[spec_type][name][spec_level_key])
def test_get_dependent_traverses_tree(self):
specs = {
'apps': {
'app1': get_app_dusty_schema(
{'depends': {'apps': ['app2']},
'repo': '',
'image': ''
}, name='app1'),
'app2': get_app_dusty_schema(
{
'depends': {'apps': ['app3']},
'repo': '',
'image': ''
}, name='app2'),
'app3': get_app_dusty_schema(
{
'depends': {'apps': ['app4', 'app5']},
'repo': '',
'image': ''
}, name='app3'),
'app4': get_app_dusty_schema(
{
'depends': {'apps': ['app5']},
'repo': '',
'image': ''
}, name='app4'),
'app5': get_app_dusty_schema({'repo': '', 'image': ''}, name='app5'),
'app6': get_app_dusty_schema({'repo': '', 'image': ''}, name='app6')
}
}
self.assertEqual(set(['app2', 'app3', 'app4', 'app5']),
spec_assembler._get_dependent('apps', 'app1', specs, 'apps'))
def test_get_dependent_root_type(self):
specs = {
'apps': {
'app1': get_app_dusty_schema(
{'depends': {
'apps': ['app2'],
'libs': ['lib1']},
'repo': '',
'image': ''
}, name='app1'),
'app2': get_app_dusty_schema(
{'repo': '',
'image': ''
}, name='app2')
},
'libs': {
'lib1': get_lib_dusty_schema(
{'depends': {'libs': ['lib2']},
'repo': ''}, name='lib1'),
'lib2': get_lib_dusty_schema({'repo': ''}, name='lib2'),
'lib3': get_lib_dusty_schema({'repo': ''}, name='lib3')
}
}
self.assertEqual(set(['lib1', 'lib2']),
spec_assembler._get_dependent('libs', 'app1', specs, 'apps'))
class TestSpecAssemblerGetRepoTestCases(DustyTestCase):
def test_get_repo_of_app_or_service_app(self):
self.assertEqual(spec_assembler.get_repo_of_app_or_library('app-a'), Repo('github.com/app/a'))
def test_get_repo_of_app_or_service_lib(self):
self.assertEqual(spec_assembler.get_repo_of_app_or_library('lib-a'), Repo('github.com/lib/a'))
def test_get_repo_of_app_or_service_neither(self):
with self.assertRaises(KeyError):
spec_assembler.get_repo_of_app_or_library('lib-b')
class TestGetExpandedLibSpecs(DustyTestCase):
def test_get_expanded_lib_specs_1(self):
specs = {
'apps': {
'app1': get_app_dusty_schema({
'depends': {
'libs': ['lib1', 'lib2'],
'apps': ['app2']
},
'repo': '',
'image': ''
}, name='app1'),
'app2': get_app_dusty_schema({
'depends': {},
'repo': '',
'image': ''
}, name='app2')
},
'libs': {
'lib1': get_lib_dusty_schema({
'depends': {
'libs': ['lib2']
},
'repo': ''
}, name='lib1'),
'lib2': get_lib_dusty_schema({
'depends': {
'libs': ['lib3']
},
'repo': ''
}, name='lib2'),
'lib3': get_lib_dusty_schema({
'depends': {},
'repo': ''
}, name='lib3')
}
}
expected_expanded_specs = {
'apps': {
'app1': {
'commands': {
'always': ['sleep 1'],
'once': []
},
'depends': {
'libs': set(['lib1', 'lib2', 'lib3']),
'apps': ['app2'],
'services': []
},
'repo': '',
'image': ''
},
'app2': {
'commands': {
'always': ['sleep 1'],
'once': []
},
'repo': '',
'image': ''
}
},
'libs': {
'lib1': {
'depends': {
'libs': set(['lib2', 'lib3'])
},
'repo': ''
},
'lib2': {
'depends': {
'libs': set(['lib3'])
},
'repo': ''
},
'lib3': {
'repo': ''
}
}
}
spec_assembler._get_expanded_libs_specs(specs)
for spec_type in ('apps', 'libs'):
for name, spec in expected_expanded_specs[spec_type].iteritems():
for spec_level_key, value in spec.iteritems():
self.assertEquals(specs[spec_type][name][spec_level_key], value)
class TestGetDependentRepos(DustyTestCase):
@patch('dusty.compiler.spec_assembler.get_specs')
def test_get_same_container_repos_app(self, fake_get_specs):
fake_get_specs.return_value = self.make_test_specs(apply_required_keys(
{'apps': {'app1': {
'commands': {
'always': ['sleep 10']
},
'depends': {'apps': ['app2', 'app3'],
'libs': ['lib1']},
'repo': '/gc/app1'},
'app2': {
'commands': {
'always': ['sleep 10']
},
'depends': {'apps': ['app4'],
'libs': []},
'repo': '/gc/app2'
},
'app3': {
'commands': {
'always': ['sleep 10']
},
'depends': {'apps': [], 'libs': []}, 'repo': '/gc/app3'
},
'app4': {
'commands': {
'always': ['sleep 10']
},
'depends': {'apps': [], 'libs': []}, 'repo': '/gc/app4'}
},
'libs': {'lib1': {'depends': {'libs': ['lib2']}, 'repo': '/gc/lib1'},
'lib2': {'depends': {'libs': []}, 'repo': '/gc/lib2'}}}))
self.assertEquals(set(spec_assembler.get_same_container_repos('app1')),
set([Repo('/gc/app1'), Repo('/gc/lib1'), Repo('/gc/lib2')]))
@patch('dusty.compiler.spec_assembler.get_specs')
def test_get_same_container_repos_app_without_repo(self, fake_get_specs):
fake_get_specs.return_value = self.make_test_specs(apply_required_keys({
'apps': {
'app1': {
'depends': {'apps': ['app2', 'app3'],
'libs': ['lib1']},
'commands': {
'always': ['sleep 10']
},
},
'app2': {
'depends': {'apps': ['app4'],
'libs': []},
'commands': {
'always': ['sleep 10']
},
'repo': '/gc/app2'
},
'app3': {
'depends': {'apps': [], 'libs': []},
'repo': '/gc/app3',
'commands': {
'always': ['sleep 10']
},
},
'app4': {
'depends': {'apps': [], 'libs': []},
'repo': '/gc/app4',
'commands': {
'always': ['sleep 10']
},
}
},
'libs': {'lib1': {'depends': {'libs': ['lib2']}, 'repo': '/gc/lib1'},
'lib2': {'depends': {'libs': []}, 'repo': '/gc/lib2'}}}))
self.assertEquals(set(spec_assembler.get_same_container_repos('app1')),
set([Repo('/gc/lib1'), Repo('/gc/lib2')]))
@patch('dusty.compiler.spec_assembler.get_specs')
def test_get_same_container_repos_lib(self, fake_get_specs):
fake_get_specs.return_value = self.make_test_specs(apply_required_keys({
'apps': {'app1':
{'depends': {'apps': ['app2', 'app3'],
'libs': ['lib1']},
'commands': {
'always': ['sleep 10']
},
'repo': '/gc/app1'},
'app2':
{'depends': {'apps': ['app4'],
'libs': []},
'commands': {
'always': ['sleep 10']
},
'repo': '/gc/app2'},
'app3': {
'depends': {'apps': [], 'libs': []},
'repo': '/gc/app3',
'commands': {
'always': ['sleep 10']
},
},
'app4': {
'depends': {'apps': [], 'libs': []},
'repo': '/gc/app4',
'commands': {
'always': ['sleep 10']
},
}
},
'libs': {'lib1': {'depends': {'libs': ['lib2']}, 'repo': '/gc/lib1'},
'lib2': {'depends': {'libs': []}, 'repo': '/gc/lib2'}}}))
self.assertEquals(set(spec_assembler.get_same_container_repos('lib1')),
set([Repo('/gc/lib1'), Repo('/gc/lib2')]))
| {
"repo_name": "gamechanger/dusty",
"path": "tests/unit/compiler/test_test_cases.py",
"copies": "1",
"size": "16336",
"license": "mit",
"hash": -2299166165942645000,
"line_mean": 48.6534954407,
"line_max": 116,
"alpha_frac": 0.3213761019,
"autogenerated": false,
"ratio": 5.202547770700637,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.004482355286911207,
"num_lines": 329
} |
from functools import wraps
from multiprocessing import Process, get_context
from multiprocessing.queues import Queue
from threading import Thread
import time
from multiprocessing import Lock
class BlockedQueue(Queue):
def __init__(self, maxsize=-1, block=True, timeout=None):
self.block = block
self.timeout = timeout
super().__init__(maxsize, ctx=get_context())
def put(self, obj, block=True, timeout=None):
super().put(obj, block=self.block, timeout=self.timeout)
def get(self, block=True, timeout=None):
if self.empty():
return None
return super().get(block=self.block, timeout=self.timeout)
def _execute(queue, f, *args, **kwargs):
try:
queue.put(f(*args, **kwargs))
except Exception as e:
queue.put(e)
def threaded(timeout=None, block=True):
def decorator(func):
queue = BlockedQueue(1, block, timeout)
@wraps(func)
def wrapper(*args, **kwargs):
args = (queue, func) + args
t = Thread(target=_execute, args=args, kwargs=kwargs)
t.start()
return queue.get()
return wrapper
return decorator
def processed(timeout=None, block=True):
def decorator(func):
queue = BlockedQueue(1, block, timeout)
@wraps(func)
def wrapper(*args, **kwargs):
args = (queue, func) + args
p = Process(target=_execute, args=args, kwargs=kwargs)
p.start()
return queue.get()
return wrapper
return decorator
def async_call(async_api=Thread, timeout=None, block=True):
def decorator(func):
queue = BlockedQueue(1, block, timeout)
@wraps(func)
def wrapper(*args, **kwargs):
args = (queue, func) + args
async = async_api(target=_execute, args=args, kwargs=kwargs)
async.start()
return queue.get()
return wrapper
return decorator
def scheduled(period, delay=None, loop_count=None):
delay = delay or 0
loop_count = loop_count or 0
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
counter = 0
time.sleep(delay)
while True:
start = time.time()
if loop_count and loop_count > 0:
if counter == loop_count:
break
counter += 1
func(*args, **kwargs)
run_time = time.time() - start
if run_time < period:
time.sleep(period - run_time)
return wrapper
return decorator
simple_lock = Lock()
def synchronized(lock=simple_lock):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
with lock:
return func(*args, **kwargs)
return wrapper
return decorator
if __name__ == '__main__':
@threaded(block=False)
def test1(x):
time.sleep(x)
print("test 1")
@processed(block=False)
def test2(x):
time.sleep(x)
print("test 2")
@threaded(block=False)
@scheduled(period=2, loop_count=3)
def test3(x):
time.sleep(x)
print("test 3")
@threaded()
@scheduled(period=1, loop_count=2)
@processed()
def test_pow(x):
print(x * x)
@threaded()
@synchronized()
def lock_test_a():
print('lock_test_a')
@async_call(Thread)
@synchronized()
def lock_test_b():
print('lock_test_b')
test3(0)
test1(2)
test2(1)
test_pow(5)
lock_test_a()
lock_test_b()
| {
"repo_name": "samuelsh/pyFstress",
"path": "logger/asynx.py",
"copies": "2",
"size": "3673",
"license": "mit",
"hash": -6921852615160614000,
"line_mean": 21.3963414634,
"line_max": 72,
"alpha_frac": 0.5551320447,
"autogenerated": false,
"ratio": 3.919957310565635,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5475089355265634,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from multiprocessing import Process
import webbrowser
from .utils import processing_func_name
def processing_function(func):
"""Decorator for turning Sketch methods into Processing functions.
Marks the function it's decorating as a processing function by camel
casing the name of the function (to follow Processing naming conventions)
and attaching the new name to the function object as 'processing_name'.
It also DRY's up the code a bit by creating the command dict from the
result of calling the wrapped function and appends it to the Sketch
object's frame.
"""
# Camel case the name to match the Processing naming conventions
processing_name = processing_func_name(func.__name__)
# Create a wrapper function that gets the returned args from the real
# function and creates a new command dict and adds it to the frame queue.
@wraps(func)
def wrapper(self, *args, **kwargs):
cmd = {
'name': processing_name,
'args': func(self, *args, **kwargs)
}
self.frame.setdefault('commands', []).append(cmd)
# Mark the method as a Processing function by adding its counterparts name
wrapper.processing_name = processing_name
return wrapper
class Sketch(object):
frame_rate = 60
width = 100
height = 100
def setup(self):
pass
def draw(self):
pass
def __init__(self):
self.reset()
self.setup()
def reset(self):
"""Resets the state of the system (i.e., the current frame dict).
This method is meant to be called between calls to the draw method
as a means of clearing the current frame. The frame is the set of
commands to be sent to the client for drawing the current frame.
"""
self._frame = {}
@processing_function
def point(self, x, y):
return [x, y]
@processing_function
def background(self, *args):
return self._parse_color(*args)
@processing_function
def fill(self, *args):
return self._parse_color(*args)
@processing_function
def stroke(self, *args):
return self._parse_color(*args)
@processing_function
def no_stroke(self):
return self._parse_color(0, 0)
@processing_function
def stroke_weight(self, weight):
return [weight]
@processing_function
def translate(self, x, y):
return [x, y]
@processing_function
def line(self, x1, y1, x2, y2):
return [x1, y1, x2, y2]
@processing_function
def rect(self, x, y, width, height):
return [x, y, width, height]
@processing_function
def ellipse(self, x, y, width, height):
return [x, y, width, height]
def _parse_color(self, *args):
if len(args) == 1:
color = [args[0]]*3
elif len(args) == 2:
color = [args[0]]*3 + [args[1]]
else:
color = args
return color
@property
def processing_functions(self):
for member_name in dir(self):
obj = getattr(self, member_name)
if hasattr(obj, 'processing_name'):
yield obj
@property
def frame(self):
self._frame.update({
'canvas': {
'width': self.width,
'height': self.height
}
})
return self._frame
@frame.setter
def frame(self, frame):
self._frame = frame
| {
"repo_name": "croach/processing.py",
"path": "lib/p5/sketch.py",
"copies": "2",
"size": "3501",
"license": "mit",
"hash": 2196176670442872800,
"line_mean": 25.9307692308,
"line_max": 78,
"alpha_frac": 0.606398172,
"autogenerated": false,
"ratio": 4.109154929577465,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 130
} |
from functools import wraps
from .named import namedtuple
from .ast import *
@namedtuple
def Intermediate(kind, originalindex, value):
assert kind in {'bytecode', 'if', 'for', 'do', 'label'}
def get_labels(bc):
for i, b in enumerate(bc):
if b[0].startswith('jump'):
yield b[1]
def into_list(f):
@wraps(f)
def _f(*args, **kwargs):
return list(f(*args, **kwargs))
return _f
@into_list
def annotate_bytecode(bc):
labels = set(get_labels(bc))
for i, b in enumerate(bc):
if i in labels:
yield Intermediate('label', i, i)
if b[0] == 'lambda':
yield Intermediate('do', i, annotate_bytecode(b[1]))
else:
yield Intermediate('bytecode', i, b)
def for_nodes(abc):
i = 0
while i < len(abc):
node = abc[i]
if node.kind == 'bytecode' and node.value[0] == 'jump' and node.value[1] < node.originalindex:
endi = i
while not (abc[i].kind == 'label' and abc[i].originalindex == node.value[1]):
i -= 1
assert i >= 0
abc[i + 1:endi + 1] = Intermediate('for', node.originalindex, abc[i + 4:endi]),
elif node.kind == 'do':
for_nodes(node.value)
i += 1
def if_nodes(abc):
i = len(abc) - 1
while i >= 0:
node = abc[i]
if node.kind == 'bytecode' and node.value[0] == 'jump if nil':
starti = i
while not (abc[i].kind == 'label' and abc[i].originalindex == node.value[1]):
i += 1
assert i < len(abc)
if abc[i - 1].kind == 'bytecode' and abc[i - 1].value[0] == 'jump': # else
i2 = i
while not (abc[i2].kind == 'label' and abc[i2].originalindex == abc[i - 1].value[1]):
i2 += 1
assert i2 <= len(abc), (i2, len(abc), abc)
if i2 == len(abc):
break
abc[starti:i2] = Intermediate('if', node.originalindex, (abc[starti + 1:i - 1], abc[i + 1:i2])),
else: # no else
abc[starti:i] = Intermediate('if', node.originalindex, (abc[starti + 1:i], None)),
i = starti
elif node.kind in {'for', 'do'}:
if_nodes(node.value)
i -= 1
@into_list
def get_nodes(abc):
i = 0
while i < len(abc):
node = abc[i]
if node.kind == 'label':
pass
elif node.kind in {'for', 'do'}:
yield Intermediate(node.kind, node.originalindex, get_nodes(node.value))
elif node.kind == 'if':
yield Intermediate(node.kind, node.originalindex, (get_nodes(node.value[0]), get_nodes(node.value[1])))
else:
yield node
i += 1
@namedtuple
def Nodicle(name, value=None):
pass
def make_intermediate_nodes(bc):
abc = annotate_bytecode(bc)
for_nodes(abc)
if_nodes(abc)
return get_nodes(abc)
def build_ast(nodes):
build_stack = []
for node in nodes:
if node.kind == 'bytecode':
c = node.value
opc = c[0]
if opc == 'lit':
v = c[1]
if v is None:
build_stack.append(Nil())
elif isinstance(v, str):
build_stack.append(StrLit([RegFrag(v)]))
elif isinstance(v, int):
build_stack.append(Int(v))
elif isinstance(v, Symbol):
build_stack.append(Sym(v))
else:
assert not 'reachable'
elif opc == 'return':
build_stack.append(ReturnValue(build_stack.pop()))
elif opc == 'dup':
build_stack.append(Nodicle(opc))
elif opc == 'get name':
build_stack.append(Name(c[1]))
elif opc == 'get index':
index = build_stack.pop()
coll = build_stack.pop()
if isinstance(coll, Nodicle):
if coll.name == 'dup':
build_stack.append(Nodicle('destructuring', [index]))
elif coll.name == 'destructuring':
build_stack.append(coll)
build_stack.append(Nodicle('destructuring tail', index))
else:
assert not 'reachable'
else:
build_stack.append(Index(coll, index))
elif opc == 'get attr':
build_stack.append(Attr(build_stack.pop(), c[1]))
elif opc == 'get attr raw':
build_stack.append(AttrGet(build_stack.pop(), c[1]))
elif opc == 'new table':
build_stack.append(TableLit([]))
elif opc == 'set name':
value = build_stack.pop()
name = Name(c[1])
if isinstance(value, Nodicle):
if value.name == 'destructuring':
if c[1] == value.value[0].value:
name = Sym(c[1])
value.value.append(name)
build_stack.append(value)
elif value.name == 'destructuring tail':
if c[1] == value.value.value:
name = Sym(c[1])
items = [(value.value, name)]
while isinstance(build_stack[-1], Nodicle) and build_stack[-1].name == 'destructuring':
items.append(tuple(build_stack.pop().value))
items.reverse()
build_stack.append(Assign(TableLit(items), '=', build_stack.pop()))
else:
assert value.name == 'dup' and isinstance(build_stack[-1], UnOpS)
else:
build_stack.append(Assign(name, '=', value))
elif opc == 'set index':
value = build_stack.pop()
index = build_stack.pop()
coll = build_stack.pop()
if isinstance(coll, Nodicle) and coll.name == 'dup':
coll = build_stack[-1]
coll.value.append((index, value))
else:
build_stack.append(Assign(Index(coll, index), '=', value))
elif opc == 'set attr':
value = build_stack.pop()
coll = build_stack.pop()
build_stack.append(Assign(Attr(coll, c[1]), '=', value))
elif opc == 'set attr raw':
value = build_stack.pop()
coll = build_stack.pop()
build_stack.append(Assign(AttrGet(coll, c[1]), '=', value))
elif opc == 'call':
func = build_stack.pop()
arg = build_stack.pop()
build_stack.append(FuncCall(func, arg))
elif opc == 'binop':
right = build_stack.pop()
left = build_stack.pop()
build_stack.append(BinOp(left, c[1], right))
elif opc == 'unop':
right = build_stack.pop()
op = c[1]
build_stack.append((UnOpS if op in {'++', '--'} else UnOp)(op, right))
elif opc == 'drop':
pass
elif opc == 'convert to string':
build_stack.append(Nodicle(opc, build_stack.pop()))
elif opc == 'collect string':
m = build_stack.pop()
c = []
while not isinstance(m, Nil):
if isinstance(m, StrLit):
c.append(m[0][0])
elif isinstance(m, Nodicle) and m.name == 'convert to string':
c.append(m.value)
m = build_stack.pop()
build_stack.append(StrLit(list(reversed(c))))
else:
assert not 'reachable', opc
elif node.kind == 'do':
build_stack.append(Do(build_ast(node.value)))
elif node.kind == 'for':
it = build_stack.pop()
retval = build_stack.pop()
assert isinstance(retval, Nil)
# remove boilerplate
del node.value[-6:]
node.value.pop(0)
# collect item names
namelist = []
while node.value[0].kind == 'bytecode' and node.value[0].value == ('dup',):
namelist.append(node.value[2].value[1])
del node.value[:3]
# finally construct AST node
build_stack.append(For(namelist, it, build_ast(node.value)))
elif node.kind == 'if':
cond = build_stack.pop()
has_else = len(node.value[1]) > 1 or node.value[1][0].kind != 'bytecode' or node.value[1][0].value != ('lit', None)
build_stack.append(If(cond, build_ast(node.value[0]), build_ast(node.value[1]) if has_else else None))
else:
assert not 'reachable'
if len(build_stack) > 1 and isinstance(build_stack[-1], Nil) and isinstance(build_stack[-2], (Assign, ReturnValue)):
build_stack.pop()
return build_stack
# build exps backwards
# then do tablelit forwards (check assigment to dup)
| {
"repo_name": "gvx/isle",
"path": "read_bytecode.py",
"copies": "1",
"size": "9272",
"license": "isc",
"hash": -8009722888555481000,
"line_mean": 38.9655172414,
"line_max": 127,
"alpha_frac": 0.4762726488,
"autogenerated": false,
"ratio": 3.90071518721077,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9857892870838328,
"avg_score": 0.0038189930344882427,
"num_lines": 232
} |
from functools import wraps
from operator import attrgetter
from django.db import connections, transaction, IntegrityError
from django.db.models import signals, sql
from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE
from django.utils.datastructures import SortedDict
class ProtectedError(IntegrityError):
def __init__(self, msg, protected_objects):
self.protected_objects = protected_objects
super(ProtectedError, self).__init__(msg, protected_objects)
def CASCADE(collector, field, sub_objs, using):
collector.collect(sub_objs, source=field.rel.to,
source_attr=field.name, nullable=field.null)
if field.null and not connections[using].features.can_defer_constraint_checks:
collector.add_field_update(field, None, sub_objs)
def PROTECT(collector, field, sub_objs, using):
raise ProtectedError("Cannot delete some instances of model '%s' because "
"they are referenced through a protected foreign key: '%s.%s'" % (
field.rel.to.__name__, sub_objs[0].__class__.__name__, field.name
),
sub_objs
)
def SET(value):
if callable(value):
def set_on_delete(collector, field, sub_objs, using):
collector.add_field_update(field, value(), sub_objs)
else:
def set_on_delete(collector, field, sub_objs, using):
collector.add_field_update(field, value, sub_objs)
return set_on_delete
SET_NULL = SET(None)
def SET_DEFAULT(collector, field, sub_objs, using):
collector.add_field_update(field, field.get_default(), sub_objs)
def DO_NOTHING(collector, field, sub_objs, using):
pass
def force_managed(func):
@wraps(func)
def decorated(self, *args, **kwargs):
if not transaction.is_managed(using=self.using):
transaction.enter_transaction_management(using=self.using)
forced_managed = True
else:
forced_managed = False
try:
func(self, *args, **kwargs)
if forced_managed:
transaction.commit(using=self.using)
else:
transaction.commit_unless_managed(using=self.using)
finally:
if forced_managed:
transaction.leave_transaction_management(using=self.using)
return decorated
class Collector(object):
def __init__(self, using):
self.using = using
# Initially, {model: set([instances])}, later values become lists.
self.data = {}
self.batches = {} # {model: {field: set([instances])}}
self.field_updates = {} # {model: {(field, value): set([instances])}}
self.dependencies = {} # {model: set([models])}
def add(self, objs, source=None, nullable=False, reverse_dependency=False):
"""
Adds 'objs' to the collection of objects to be deleted. If the call is
the result of a cascade, 'source' should be the model that caused it
and 'nullable' should be set to True, if the relation can be null.
Returns a list of all objects that were not already collected.
"""
if not objs:
return []
new_objs = []
model = objs[0].__class__
instances = self.data.setdefault(model, set())
for obj in objs:
if obj not in instances:
new_objs.append(obj)
instances.update(new_objs)
# Nullable relationships can be ignored -- they are nulled out before
# deleting, and therefore do not affect the order in which objects have
# to be deleted.
if new_objs and source is not None and not nullable:
if reverse_dependency:
source, model = model, source
self.dependencies.setdefault(source, set()).add(model)
return new_objs
def add_batch(self, model, field, objs):
"""
Schedules a batch delete. Every instance of 'model' that is related to
an instance of 'obj' through 'field' will be deleted.
"""
self.batches.setdefault(model, {}).setdefault(field, set()).update(objs)
def add_field_update(self, field, value, objs):
"""
Schedules a field update. 'objs' must be a homogenous iterable
collection of model instances (e.g. a QuerySet).
"""
if not objs:
return
model = objs[0].__class__
self.field_updates.setdefault(
model, {}).setdefault(
(field, value), set()).update(objs)
def collect(self, objs, source=None, nullable=False, collect_related=True,
source_attr=None, reverse_dependency=False):
"""
Adds 'objs' to the collection of objects to be deleted as well as all
parent instances. 'objs' must be a homogenous iterable collection of
model instances (e.g. a QuerySet). If 'collect_related' is True,
related objects will be handled by their respective on_delete handler.
If the call is the result of a cascade, 'source' should be the model
that caused it and 'nullable' should be set to True, if the relation
can be null.
If 'reverse_dependency' is True, 'source' will be deleted before the
current model, rather than after. (Needed for cascading to parent
models, the one case in which the cascade follows the forwards
direction of an FK rather than the reverse direction.)
"""
new_objs = self.add(objs, source, nullable,
reverse_dependency=reverse_dependency)
if not new_objs:
return
model = new_objs[0].__class__
# Recursively collect parent models, but not their related objects.
# These will be found by meta.get_all_related_objects()
for parent_model, ptr in model._meta.parents.iteritems():
if ptr:
parent_objs = [getattr(obj, ptr.name) for obj in new_objs]
self.collect(parent_objs, source=model,
source_attr=ptr.rel.related_name,
collect_related=False,
reverse_dependency=True)
if collect_related:
for related in model._meta.get_all_related_objects(include_hidden=True):
field = related.field
if related.model._meta.auto_created:
self.add_batch(related.model, field, new_objs)
else:
sub_objs = self.related_objects(related, new_objs)
if not sub_objs:
continue
field.rel.on_delete(self, field, sub_objs, self.using)
# TODO This entire block is only needed as a special case to
# support cascade-deletes for GenericRelation. It should be
# removed/fixed when the ORM gains a proper abstraction for virtual
# or composite fields, and GFKs are reworked to fit into that.
for relation in model._meta.many_to_many:
if not relation.rel.through:
sub_objs = relation.bulk_related_objects(new_objs, self.using)
self.collect(sub_objs,
source=model,
source_attr=relation.rel.related_name,
nullable=True)
def related_objects(self, related, objs):
"""
Gets a QuerySet of objects related to ``objs`` via the relation ``related``.
"""
return related.model._base_manager.using(self.using).filter(
**{"%s__in" % related.field.name: objs}
)
def instances_with_model(self):
for model, instances in self.data.iteritems():
for obj in instances:
yield model, obj
def sort(self):
sorted_models = []
models = self.data.keys()
while len(sorted_models) < len(models):
found = False
for model in models:
if model in sorted_models:
continue
dependencies = self.dependencies.get(model)
if not (dependencies and dependencies.difference(sorted_models)):
sorted_models.append(model)
found = True
if not found:
return
self.data = SortedDict([(model, self.data[model])
for model in sorted_models])
@force_managed
def delete(self):
# sort instance collections
for model, instances in self.data.items():
self.data[model] = sorted(instances, key=attrgetter("pk"))
# if possible, bring the models in an order suitable for databases that
# don't support transactions or cannot defer contraint checks until the
# end of a transaction.
self.sort()
# send pre_delete signals
for model, obj in self.instances_with_model():
if not model._meta.auto_created:
signals.pre_delete.send(
sender=model, instance=obj, using=self.using
)
# update fields
for model, instances_for_fieldvalues in self.field_updates.iteritems():
query = sql.UpdateQuery(model)
for (field, value), instances in instances_for_fieldvalues.iteritems():
query.update_batch([obj.pk for obj in instances],
{field.name: value}, self.using)
# reverse instance collections
for instances in self.data.itervalues():
instances.reverse()
# delete batches
for model, batches in self.batches.iteritems():
query = sql.DeleteQuery(model)
for field, instances in batches.iteritems():
query.delete_batch([obj.pk for obj in instances], self.using, field)
# delete instances
for model, instances in self.data.iteritems():
query = sql.DeleteQuery(model)
pk_list = [obj.pk for obj in instances]
query.delete_batch(pk_list, self.using)
# send post_delete signals
for model, obj in self.instances_with_model():
if not model._meta.auto_created:
signals.post_delete.send(
sender=model, instance=obj, using=self.using
)
# update collected instances
for model, instances_for_fieldvalues in self.field_updates.iteritems():
for (field, value), instances in instances_for_fieldvalues.iteritems():
for obj in instances:
setattr(obj, field.attname, value)
for model, instances in self.data.iteritems():
for instance in instances:
setattr(instance, model._meta.pk.attname, None)
| {
"repo_name": "skevy/django",
"path": "django/db/models/deletion.py",
"copies": "2",
"size": "10834",
"license": "bsd-3-clause",
"hash": -8947212117274516000,
"line_mean": 39.2750929368,
"line_max": 84,
"alpha_frac": 0.5926712202,
"autogenerated": false,
"ratio": 4.431083844580777,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007634226093045544,
"num_lines": 269
} |
from functools import wraps
from operator import attrgetter
from django.db import connections, transaction, IntegrityError
from django.db.models import signals, sql
from django.utils.datastructures import SortedDict
from django.utils import six
class ProtectedError(IntegrityError):
def __init__(self, msg, protected_objects):
self.protected_objects = protected_objects
super(ProtectedError, self).__init__(msg, protected_objects)
def CASCADE(collector, field, sub_objs, using):
collector.collect(sub_objs, source=field.rel.to,
source_attr=field.name, nullable=field.null)
if field.null and not connections[using].features.can_defer_constraint_checks:
collector.add_field_update(field, None, sub_objs)
def PROTECT(collector, field, sub_objs, using):
raise ProtectedError("Cannot delete some instances of model '%s' because "
"they are referenced through a protected foreign key: '%s.%s'" % (
field.rel.to.__name__, sub_objs[0].__class__.__name__, field.name
),
sub_objs
)
def SET(value):
if callable(value):
def set_on_delete(collector, field, sub_objs, using):
collector.add_field_update(field, value(), sub_objs)
else:
def set_on_delete(collector, field, sub_objs, using):
collector.add_field_update(field, value, sub_objs)
return set_on_delete
SET_NULL = SET(None)
def SET_DEFAULT(collector, field, sub_objs, using):
collector.add_field_update(field, field.get_default(), sub_objs)
def DO_NOTHING(collector, field, sub_objs, using):
pass
def force_managed(func):
@wraps(func)
def decorated(self, *args, **kwargs):
if not transaction.is_managed(using=self.using):
transaction.enter_transaction_management(using=self.using)
forced_managed = True
else:
forced_managed = False
try:
func(self, *args, **kwargs)
if forced_managed:
transaction.commit(using=self.using)
else:
transaction.commit_unless_managed(using=self.using)
finally:
if forced_managed:
transaction.leave_transaction_management(using=self.using)
return decorated
class Collector(object):
def __init__(self, using):
self.using = using
# Initially, {model: set([instances])}, later values become lists.
self.data = {}
self.batches = {} # {model: {field: set([instances])}}
self.field_updates = {} # {model: {(field, value): set([instances])}}
# Tracks deletion-order dependency for databases without transactions
# or ability to defer constraint checks. Only concrete model classes
# should be included, as the dependencies exist only between actual
# database tables; proxy models are represented here by their concrete
# parent.
self.dependencies = {} # {model: set([models])}
def add(self, objs, source=None, nullable=False, reverse_dependency=False):
"""
Adds 'objs' to the collection of objects to be deleted. If the call is
the result of a cascade, 'source' should be the model that caused it,
and 'nullable' should be set to True if the relation can be null.
Returns a list of all objects that were not already collected.
"""
if not objs:
return []
new_objs = []
model = objs[0].__class__
instances = self.data.setdefault(model, set())
for obj in objs:
if obj not in instances:
new_objs.append(obj)
instances.update(new_objs)
# Nullable relationships can be ignored -- they are nulled out before
# deleting, and therefore do not affect the order in which objects have
# to be deleted.
if source is not None and not nullable:
if reverse_dependency:
source, model = model, source
self.dependencies.setdefault(
source._meta.concrete_model, set()).add(model._meta.concrete_model)
return new_objs
def add_batch(self, model, field, objs):
"""
Schedules a batch delete. Every instance of 'model' that is related to
an instance of 'obj' through 'field' will be deleted.
"""
self.batches.setdefault(model, {}).setdefault(field, set()).update(objs)
def add_field_update(self, field, value, objs):
"""
Schedules a field update. 'objs' must be a homogenous iterable
collection of model instances (e.g. a QuerySet).
"""
if not objs:
return
model = objs[0].__class__
self.field_updates.setdefault(
model, {}).setdefault(
(field, value), set()).update(objs)
def collect(self, objs, source=None, nullable=False, collect_related=True,
source_attr=None, reverse_dependency=False):
"""
Adds 'objs' to the collection of objects to be deleted as well as all
parent instances. 'objs' must be a homogenous iterable collection of
model instances (e.g. a QuerySet). If 'collect_related' is True,
related objects will be handled by their respective on_delete handler.
If the call is the result of a cascade, 'source' should be the model
that caused it and 'nullable' should be set to True, if the relation
can be null.
If 'reverse_dependency' is True, 'source' will be deleted before the
current model, rather than after. (Needed for cascading to parent
models, the one case in which the cascade follows the forwards
direction of an FK rather than the reverse direction.)
"""
new_objs = self.add(objs, source, nullable,
reverse_dependency=reverse_dependency)
if not new_objs:
return
model = new_objs[0].__class__
# Recursively collect concrete model's parent models, but not their
# related objects. These will be found by meta.get_all_related_objects()
concrete_model = model._meta.concrete_model
for ptr in six.itervalues(concrete_model._meta.parents):
if ptr:
parent_objs = [getattr(obj, ptr.name) for obj in new_objs]
self.collect(parent_objs, source=model,
source_attr=ptr.rel.related_name,
collect_related=False,
reverse_dependency=True)
if collect_related:
for related in model._meta.get_all_related_objects(
include_hidden=True, include_proxy_eq=True):
field = related.field
if related.model._meta.auto_created:
self.add_batch(related.model, field, new_objs)
else:
sub_objs = self.related_objects(related, new_objs)
if not sub_objs:
continue
field.rel.on_delete(self, field, sub_objs, self.using)
# TODO This entire block is only needed as a special case to
# support cascade-deletes for GenericRelation. It should be
# removed/fixed when the ORM gains a proper abstraction for virtual
# or composite fields, and GFKs are reworked to fit into that.
for relation in model._meta.many_to_many:
if not relation.rel.through:
sub_objs = relation.bulk_related_objects(new_objs, self.using)
self.collect(sub_objs,
source=model,
source_attr=relation.rel.related_name,
nullable=True)
def related_objects(self, related, objs):
"""
Gets a QuerySet of objects related to ``objs`` via the relation ``related``.
"""
return related.model._base_manager.using(self.using).filter(
**{"%s__in" % related.field.name: objs}
)
def instances_with_model(self):
for model, instances in six.iteritems(self.data):
for obj in instances:
yield model, obj
def sort(self):
sorted_models = []
concrete_models = set()
models = six.dictkeys(self.data)
while len(sorted_models) < len(models):
found = False
for model in models:
if model in sorted_models:
continue
dependencies = self.dependencies.get(model._meta.concrete_model)
if not (dependencies and dependencies.difference(concrete_models)):
sorted_models.append(model)
concrete_models.add(model._meta.concrete_model)
found = True
if not found:
return
self.data = SortedDict([(model, self.data[model])
for model in sorted_models])
@force_managed
def delete(self):
# sort instance collections
for model, instances in self.data.items():
self.data[model] = sorted(instances, key=attrgetter("pk"))
# if possible, bring the models in an order suitable for databases that
# don't support transactions or cannot defer constraint checks until the
# end of a transaction.
self.sort()
# send pre_delete signals
for model, obj in self.instances_with_model():
if not model._meta.auto_created:
signals.pre_delete.send(
sender=model, instance=obj, using=self.using
)
# update fields
for model, instances_for_fieldvalues in six.iteritems(self.field_updates):
query = sql.UpdateQuery(model)
for (field, value), instances in six.iteritems(instances_for_fieldvalues):
query.update_batch([obj.pk for obj in instances],
{field.name: value}, self.using)
# reverse instance collections
for instances in six.itervalues(self.data):
instances.reverse()
# delete batches
for model, batches in six.iteritems(self.batches):
query = sql.DeleteQuery(model)
for field, instances in six.iteritems(batches):
query.delete_batch([obj.pk for obj in instances], self.using, field)
# delete instances
for model, instances in six.iteritems(self.data):
query = sql.DeleteQuery(model)
pk_list = [obj.pk for obj in instances]
query.delete_batch(pk_list, self.using)
# send post_delete signals
for model, obj in self.instances_with_model():
if not model._meta.auto_created:
signals.post_delete.send(
sender=model, instance=obj, using=self.using
)
# update collected instances
for model, instances_for_fieldvalues in six.iteritems(self.field_updates):
for (field, value), instances in six.iteritems(instances_for_fieldvalues):
for obj in instances:
setattr(obj, field.attname, value)
for model, instances in six.iteritems(self.data):
for instance in instances:
setattr(instance, model._meta.pk.attname, None)
| {
"repo_name": "vsajip/django",
"path": "django/db/models/deletion.py",
"copies": "1",
"size": "11445",
"license": "bsd-3-clause",
"hash": 4599691006005184500,
"line_mean": 39.7295373665,
"line_max": 86,
"alpha_frac": 0.5966797728,
"autogenerated": false,
"ratio": 4.453307392996109,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0009449209337924727,
"num_lines": 281
} |
from functools import wraps
from os import makedirs
from os.path import isdir
from future.utils import raise_with_traceback
from os import path
from requests import (
get as http_get_request,
HTTPError,
)
from requests.exceptions import (
ConnectionError,
ConnectTimeout
)
from screener.exceptions import (
InvalidTargetException,
BadStatusCode,
BAD_TARGET_ERRORS,
UnknownError,
ConnectionTimeout,
DuplicateFile,
CrawlerError)
from screener.settings import (
SUCCESS_PRINT,
FAILURE_PRINT)
logger = None
LOGGER_NAME = __name__
CRAWLER_EXCEPTION_MESSAGE = {
BadStatusCode: 'bad status code',
InvalidTargetException: 'invalid target',
ConnectionTimeout: 'connection timeout',
UnknownError: 'Unknown error, enable -v for more info'
}
INVALID_TARGET_MESSAGE = "Failed to establish a new connection"
def validate_path(*dec_args, **dec_kwargs):
def outer(wrapped):
wraps(wrapped=wrapped)
def inner(*args, **kwargs):
filename = kwargs['filename']
if not filename:
raise IOError('Invalid filename')
file_ext = dec_kwargs['ext']
if not file_ext:
raise IOError('Invalid file extension')
folder = kwargs['folder']
if not folder:
raise IOError('Invalid folder')
filename_with_exit = '{name}.{ext}'.format(
name=filename,
ext=file_ext
)
file_path = path.join(folder, filename_with_exit)
if not isdir(folder):
logger.warning('folder {dir} does not exist, creating it.'.format( # noqa
dir=folder
))
makedirs(folder)
elif path.isfile(file_path):
raise DuplicateFile('File already exist')
return wrapped(*args, **kwargs)
return inner
return outer
def validate_target(wrapped):
wraps(wrapped=wrapped)
def _check_bad_status_code(response, error_message):
try:
status_code = response.status_code
except AttributeError:
return
if status_code and (400 <= status_code <= 600):
raise BadStatusCode(msg=error_message)
def _check_bad_target(exception, error_message):
if (isinstance(exception, BAD_TARGET_ERRORS) or
(isinstance(exception, ConnectionError) and (INVALID_TARGET_MESSAGE in error_message))): # noqa
raise InvalidTargetException(msg=error_message)
def _validate_target(url):
response = None
try:
response = http_get_request(url=url)
response.raise_for_status()
except HTTPError as exc:
error_msg = str(exc.message)
_check_bad_status_code(response=response, error_message=error_msg)
raise UnknownError(msg=error_msg)
except ConnectTimeout:
raise ConnectionTimeout(msg='Connection timeout')
except (BAD_TARGET_ERRORS, ConnectionError) as exc:
error_msg = str(exc.message)
_check_bad_target(exception=exc, error_message=error_msg)
raise UnknownError(msg=error_msg)
except Exception as exc:
raise_with_traceback(UnknownError(msg=str(exc.message)))
def inner(*args, **kwargs):
url = kwargs['url']
msg = 'Validate URL {url}\t'.format(url=url)
logger.info(msg)
print(msg),
try:
_validate_target(url=url)
except CrawlerError as e:
print('{failed} ({error})'.format(
failed=FAILURE_PRINT,
error=CRAWLER_EXCEPTION_MESSAGE[e.__class__]
))
raise e
print(SUCCESS_PRINT)
logger.info('URL has been validated successfully.')
return wrapped(*args, **kwargs)
return inner
| {
"repo_name": "netanelravid/screener",
"path": "screener/utils/decorators.py",
"copies": "1",
"size": "3900",
"license": "apache-2.0",
"hash": -4352944230025209000,
"line_mean": 30.7073170732,
"line_max": 108,
"alpha_frac": 0.6030769231,
"autogenerated": false,
"ratio": 4.367301231802911,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 123
} |
from functools import wraps
from os.path import abspath
import click
from .interact.setup_user import setup_user
from . import application
from dateutil.parser import parse as parse_datetime
from datetime import datetime, timedelta
from dateutil.tz import tzlocal
dir_option = click.option(
'--dir', default=abspath('.'),
help='The Directory of the bucket you want to setup'
)
def echo_success():
click.secho(' Success: ', nl=False, fg='green')
def echo_error():
click.secho(' Error: ', nl=False, fg='red')
def echo_warning():
click.secho(' Warning: ', nl=False, fg='magenta')
def bucket_name_argument():
return click.argument('name', envvar='STABLE_WORLD_BUCKET')
def bucket_option(required=False):
return click.option(
'-b', '--bucket', required=required,
help='Name of bucket'
)
def when_option(required=False):
return click.option(
'-w', '--when', required=required,
help='Time'
)
def localnow():
return datetime.now().replace(tzinfo=tzlocal())
timeKeyWords = {
'now': localnow,
'yesterday': lambda: localnow() - timedelta(days=1),
'last week': lambda: localnow() - timedelta(days=7),
}
def datetime_type(value):
if value in timeKeyWords:
return timeKeyWords[value]()
dt = parse_datetime(value)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=tzlocal())
return dt
def ensure_login(app, hide_token=True):
if app.email and app.token:
click.echo('\n %30s: %s' % ('email', app.email))
if hide_token:
click.echo(' %30s: %s\n' % ('token', '*' * 10))
else:
click.echo(' %30s: %s\n' % ('token', app.token))
else:
setup_user(app)
def login_required(func):
"""
Require login and add options to support this
"""
@application.email_option
@application.password_option
@application.token_option
@application.pass_app
@wraps(func)
def decorator(app, **kwargs):
ensure_login(app)
func(app, **kwargs)
return decorator
def login_optional(func):
"""
Check for login and add options to support this
"""
@application.email_option
@application.password_option
@application.token_option
@application.pass_app
@wraps(func)
def decorator(app, **kwargs):
if app.email and app.password:
setup_user(app, login_only=True)
func(app, **kwargs)
return decorator
| {
"repo_name": "srossross/stable.world",
"path": "stable_world/utils.py",
"copies": "1",
"size": "2474",
"license": "bsd-2-clause",
"hash": -2973460672225561600,
"line_mean": 21.2882882883,
"line_max": 63,
"alpha_frac": 0.6289409863,
"autogenerated": false,
"ratio": 3.6064139941690962,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9735354980469096,
"avg_score": 0,
"num_lines": 111
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.