Ejemplo n.º 1
0
 def put(self, topic_id, id):
     session = Session()
     roles = oidc.user_getfield('cognito:groups') if oidc.user_getfield(
         'cognito:groups') else []
     username = oidc.user_getfield('username')
     kargs = request.get_json(silent=True)
     if not kargs.get('role'):
         json_abort(400, "role missing")
     topic = session.query(Topic).get(topic_id)
     if not topic:
         json_abort(404, "Topic doesn't exist")
     now = datetime.datetime.now()
     if topic.start_time <= now:
         json_abort(403, "Voting already started. No changes allowed")
     grant = session.query(RoleGrant).filter(
         RoleGrant.topic_id == topic_id).filter(
             RoleGrant.role.in_(roles)).all()
     if 'admin' not in roles and not grant:
         json_abort(403)
     invite = session.query(Invite).get(id)
     if kargs.get('role'):
         invite.role = kargs.get('role')
     session.add(invite)
     session.commit()
     logger.debug(invite.to_dict())
     session = Session()
     if not oidc.is_api_request():
         url = url_for('api_topic', id=topic_id)
         data = {"url": url, "message": "Success. Redirecting to %s" % url}
         return jsonify(data)
     return jsonify(invite)
Ejemplo n.º 2
0
 def post(self, topic_id):
     session = Session()
     roles = oidc.user_getfield('cognito:groups') if oidc.user_getfield(
         'cognito:groups') else []
     username = oidc.user_getfield('username')
     kargs = request.get_json(silent=True)
     if not kargs.get('desc'):
         json_abort(400, "desc missing")
     topic = session.query(Topic).get(topic_id)
     if not topic:
         json_abort(404)
     now = datetime.datetime.now()
     if topic.start_time <= now:
         json_abort(403, "Voting already started. No changes allowed")
     grant = session.query(RoleGrant).filter(
         RoleGrant.topic_id == topic_id).filter(
             RoleGrant.role.in_(roles)).all()
     logger.debug("{}, {}, {}".format(topic.user, username,
                                      topic.user != username))
     if topic.user != username and 'admin' not in roles and not grant:
         json_abort(403)
     option = TopicOption(**kargs)
     option.topic_id = topic_id
     session.add(option)
     session.commit()
     logger.debug(option.to_dict())
     session = Session()
     if not oidc.is_api_request():
         url = url_for('api_topic', id=topic_id)
         data = {"url": url, "message": "Success. Redirecting to %s" % url}
         return jsonify(data)
     return jsonify(option)
Ejemplo n.º 3
0
async def course_create(token: str = Form(...), name: str = Form(...)):
    s = Session()

    responsible = validate_user(s, token, True)

    c = Course(name=name, responsible=responsible)
    s.add(c)
    s.commit()

    return {'message': 'Course created', 'id': c.id}
Ejemplo n.º 4
0
    def save(self, data):
        if not SAVE_TO_DB:
            return
            
        session = Session()

        if not session.query(Item).filter_by(title=data['title']).first():
            obj = Item(**data)
            session.add(obj)
        session.commit()
Ejemplo n.º 5
0
    def save(self, data):
        if not SAVE_TO_DB:
            return

        session = Session()

#        if not session.query(Item).filter_by(title=data['title']).first():
        obj = Item(**data)
        session.add(obj)
        session.commit()
Ejemplo n.º 6
0
async def user_create(token: str = Form(...),
                      lms_user: str = Form(...),
                      is_prof: bool = Form(...)):
    s = Session()

    creator = validate_user(s, token, True)

    new_user = User(lms_user=lms_user, is_prof=is_prof)
    s.add(new_user)
    s.commit()

    return {'message': 'ok', 'token': new_user.token}
Ejemplo n.º 7
0
 def post(self):
     session = Session()
     data = json.loads(self.request.body.decode('utf8'))
     if data.get('id'):
         workspace = session.query(Workspace).get(data['id'])
     else:
         workspace = Workspace()
     workspace.name = data.get('name', '')
     session.add(workspace)
     session.commit()
     workspace.update_labels(session, data['labels'])
     workspace.update_urls(session, data['urls'])
     session.commit()
     self.write({'id': workspace.id})
Ejemplo n.º 8
0
def register_submit(session):
    username = bottle.request.json["username"]
    password = bottle.request.json["password"]
    email = bottle.request.json.get("email")
    sa_session = Session()
    user = User(username=username,
                password=password,
                email=email,
                slug=sa_helper.generate_slug(sa_session, User,
                                             slugify.slugify(username)))
    sa_session.add(user)
    sa_session.commit()
    session["user_id"] = user.id
    return {"success": True}
Ejemplo n.º 9
0
 def post(self):
     session = Session()
     username = oidc.user_getfield('username')
     kargs = request.get_json(silent=True)
     logger.debug(kargs)
     if not kargs.get('topic_id'):
         json_abort(400)
     topic = session.query(Topic).get(kargs['topic_id'])
     if not topic:
         json_abort(400)
     if not topic.user == username:
         json_abort(403)
     grant = RoleGrant(**kargs)
     session.add(grant)
     session.commit()
     logger.debug(grant)
     return jsonify(grant)
Ejemplo n.º 10
0
async def submit_task(course_id: int,
                      activity_id: str,
                      token: str = Form(...),
                      content: str = Form(...),
                      type: Optional[str] = Form(
                          ActivityType.multiple_choice)):
    s = Session()

    sender = validate_user(s, token, False)

    try:
        course = s.query(Course).filter(Course.id == course_id).one()
    except NoResultFound:
        raise HTTPException(status_code=404, detail='Invalid course id')

    try:
        activity = s.query(Activity).filter(
            Activity.course_id == course_id,
            Activity.course_specific_id == activity_id).one()
    except NoResultFound:
        activity = Activity(course_specific_id=activity_id,
                            type=type,
                            course=course)
        s.add(activity)

    sub = Submission(sender=sender, activity=activity, content=content)
    s.add(sub)

    try:
        correct = s.query(Submission.content).filter(
            Submission.activity == activity,
            Submission.sender.has(is_prof=True)).first()[0]
    except NoResultFound:
        correct = ""

    s.commit()
    return {
        'message': 'OK',
        'id': sub.id,
        "correct_answer": correct,
        "activity_id": activity_id,
        "content": content
    }
Ejemplo n.º 11
0
 def post(self):
     session = Session()
     username = oidc.user_getfield('username')
     roles = oidc.user_getfield('cognito:groups') if oidc.user_getfield(
         'cognito:groups') else []
     kargs = request.get_json(silent=True)
     logger.debug(kargs)
     vote_jwt = kargs.get('vote')
     if not vote_jwt:
         json_abort(400, "Vote missing")
     if not oidc.is_api_request():
         json_abort(403)
     secret = oidc.get_access_token().split('.')[-1]
     payload = jwt.decode(vote_jwt, secret, algorithms=['HS256'])
     fields = ['token', 'topic_id', 'option_id']
     for field in fields:
         if not payload.get(field):
             json_abort(400, "%s missing in token" % field)
     topic_id = payload.get('topic_id')
     topic = session.query(Topic).get(topic_id)
     if not topic:
         json_abort(404, description="Topic not found")
     now = datetime.datetime.now()
     if topic.start_time > now and topic.end_time < now:
         json_abort(400, description="Voting not begun yet")
     mapper = session.query(Mapper).filter(
         Mapper.topic_id == topic_id).filter(Mapper.user == username).all()
     if mapper:
         json_abort(409)
     invite = session.query(Invite).filter(
         Invite.topic_id == topic_id).filter(Invite.role.in_(roles)).all()
     if not invite and topic.user != username:
         json_abort(403)
     vote = Vote(topic_id=payload['topic_id'],
                 option_id=payload['option_id'],
                 token=payload['token'])
     mapper = Mapper(user=username, topic_id=topic_id)
     session.add(vote)
     session.add(mapper)
     session.commit()
     logger.debug(vote)
     return jsonify(vote)
Ejemplo n.º 12
0
def process_input(header=True):
    csv_file = open(tmp_file, 'r', encoding='utf-8')
    csv_reader = None
    try:
        csv_reader = list(csv.reader(csv_file, delimiter=','))
    except:
        print("Error in opening csv file. Please check the format/encoding!!")
        quit()
    line_no = 0
    if header:
        line_no += 1
        csv_reader = csv_reader[1:]
    session = Session()

    all_reviews = session.query(Review).all()
    reviews_set = {(review.product_id, str(review.review_text).lower())
                   for review in all_reviews}
    reviews_in_file = set()
    print("Processing input file..")
    for line in csv_reader:
        line_no += 1
        review_text = line[0]
        product_id = line[4]
        search_key = (product_id, str(review_text).lower())
        if search_key in reviews_set:
            print("Review at line: {} is already in db!!".format(line_no))
        elif search_key in reviews_in_file:
            print("Review at line: {} is duplicate in file!!".format(line_no))
        else:
            review_ob = Review(product_id, review_text)
            session.add(review_ob)
            reviews_in_file.add(search_key)

    print("Committing data...")
    session.commit()
    session.close()
    try:
        # Remove downloaded file
        os.remove(tmp_file)
    except:
        pass
Ejemplo n.º 13
0
def process_reviews():
    session = Session()
    client = language.LanguageServiceClient()
    reviews_to_analyze = session.query(Review).filter_by(
        review_analyzed=False).all()
    total = len(reviews_to_analyze)
    processed = 0
    step = 1
    throttle_limit = 500
    print("Processing Reviews...")
    print("Processed {}/{} ".format(processed, total), end='\r')
    start_time = time.time()
    one_minute = 60
    for review in reviews_to_analyze:
        try:
            analyze_review(client, review, session)
        except:
            pass
        review.review_analyzed = True
        session.add(review)
        processed += 1

        # if processed % step == 0:
        print("Processed {}/{} ".format(processed, total), end='\r')

        if processed % throttle_limit == 0:
            end_time = time.time()
            time_taken = end_time - start_time
            if time_taken < one_minute:
                time.sleep(one_minute - time_taken)
            start_time = time.time()

    print("Processed {}/{} ".format(processed, total))
    print("Committing data...")
    session.commit()
    session.close()

    print("Processed data stored successfully!!")
Ejemplo n.º 14
0
 def post(self):
     session = Session()
     data = json.loads(self.request.body.decode('utf8'))
     ws = session.query(Workspace).get(data['wsId'])
     page = session.query(Page).filter_by(
         workspace=ws.id, url=data['url']).one()
     element_label = session.query(ElementLabel).filter_by(
         page=page.id, selector=data['selector']).one_or_none()
     if data.get('label') is not None:
         label = session.query(Label).filter_by(
             workspace=ws.id, text=data['label']).one()
         if element_label is None:
             element_label = ElementLabel(
                 page=page.id,
                 selector=data['selector'],
                 label=label.id)
         else:
             element_label.label = label.id
         session.add(element_label)
     elif element_label is not None:
         session.delete(element_label)
     session.commit()
     self.write({'ok': True})
Ejemplo n.º 15
0
 def post(self):
   session = Session()
   username = oidc.user_getfield('username')
   kargs = request.get_json(silent=True)
   logger.debug(kargs)
   topic = Topic(
     **kargs 
   )
   now = datetime.datetime.now()
   minimum = datetime.timedelta(minutes=5)
   if (parse(topic.start_time, yearfirst=True) - now) < minimum:
     json_abort(400, "You can only create a topic with minimum 5 minute in advance.")
   if topic.start_time >= topic.end_time:
     json_abort(400, "End time can not be less than Start time.")
   topic.user = username
   session.add(topic)
   session.commit()
   logger.debug(topic.to_dict())
   session = Session()
   if not oidc.is_api_request():
     url = url_for('api_topic', id=int(topic.id))
     data = { "url": url, "message": "Success. Redirecting to %s" % url }         
     return jsonify(data) 
   return jsonify(topic)
Ejemplo n.º 16
0
from sqlalchemy import create_engine
from sqlalchemy.exc import IntegrityError
from fact_models import FactArtistByYear, FactGenreByYear, FactSongByYear
from data_processor import DataProcessor
from config import Session, dataSource

session = Session()

dirname = os.path.dirname(__file__)
ds = DataProcessor(os.path.join(dirname, dataSource))
ds.process()

for i, row in ds.artistsByYear().iterrows():
    record = FactArtistByYear(year=row[0], artist=row[1], titles=row[2])
    try:
        session.add(record)
        session.commit()
    except IntegrityError:
        print('FactArtistByYear Record exists for year {}'.format(row[0]))
        session.rollback()
query = session.query(FactArtistByYear)
print('{} records exist in FactArtistByYear'.format(query.count()))

for i, row in ds.genreByYear().iterrows():
    record = FactGenreByYear(year=row[0], genre=row[1], titles=row[2])
    try:
        session.add(record)
        session.commit()
    except IntegrityError:
        print('FactGenreByYear Record exists for year {}'.format(row[0]))
        session.rollback()
Ejemplo n.º 17
0
session = Session()

name='main module'

try:
    m = session.query(LightModule).filter(LightModule.name==name).one()
    session.delete(m)
except NoResultFound, e:
    pass
m = LightModule(name="first pi lit", hostname="raspberrypi", location="lab")
s1 = Segment(num_pixels=60, module_startpixel=0, forwards=False)
s1.strip_startpixel=0
s2 = Segment(num_pixels=60, module_startpixel=64, forwards=True)
s2.strip_startpixel=60
m.segments = [s1, s2]
strip = Strip(length=124, name='main1')
strip.segments = [s1, s2]
session.add(m)

m = LightModule(name="second pi lit", hostname="secondpilit", location="lab")
s1 = Segment(num_pixels=64, module_startpixel=0, forwards=False)
s1.strip_startpixel=0
s2 = Segment(num_pixels=64, module_startpixel=64, forwards=True)
s2.strip_startpixel=64
m.segments = [s1, s2]
strip = Strip(length=128, name='main2')
strip.segments = [s1, s2]
session.add(m)
session.commit()
Ejemplo n.º 18
0
# 2 - generer la base de données
Base.metadata.create_all(engine)

# 3 - creer une nouvelle session
session = Session()

user1 = Utilisateur("kenna", "amine", date(1994, 6, 1))
user2 = Utilisateur("baali", "kaoutar", date(1997, 1, 11))

ville1 = Ville("Paris", "Paris", "ile de france", 75000)
ville2 = Ville("Chatenay Malabry", "Haut seine", "ile de france", 92290)

bien1 = BienImmobilier("appartement", "tres jolie", "appt", user1, ville1)
bien2 = BienImmobilier("villa", "tres belle", "vl", user2, ville2)

piece1 = Piece(20, "vaste", bien1)



session.add(user1)
session.add(user2)
session.add(ville1)
session.add(ville2)
session.add(bien1)
session.add(bien2)
session.add(piece1)

session.commit()
session.close()
Ejemplo n.º 19
0
#%%
import sqlalchemy
from sqlalchemy.orm import sessionmaker

import models

from config import Session

#%%

s = Session()
#%%
u = models.User(lms_user='******', is_prof=True, token='alks')
s.add(u)
s.commit()
# %%
print(sess.query(models.User).all())

# %%

u = s.query(models.User).first()

c = models.Course(name='test', responsible=u)
s.add(c)
s.commit()

# %%

a = models.Activity(course_specific_id='at1', course=c)
s.add(a)
s.commit()