Ejemplo n.º 1
0
def edit_mooc(field_id, mooc_id):
    """Edit a MOOC"""
    field = session.query(Field).filter_by(id=field_id).first()
    mooc = session.query(MOOC).filter_by(id=mooc_id, field_id=field_id).first()

    # Verify if he is the user who created it
    if mooc.user_id == login_session['user_id']:
        if request.method == 'POST':
            if request.form.get('title'):
                mooc.title = request.form.get('title')
            if request.form.get('provider'):
                mooc.provider = request.form.get('provider')
            if request.form.get('creator'):
                mooc.creator = request.form.get('creator')
            if request.form.get('level'):
                mooc.level = request.form.get('level')
            if request.form.get('url'):
                mooc.url = request.form.get('url')
            if request.form.get('description'):
                mooc.description = request.form.get('description')
            if request.form.get('image'):
                mooc.image = request.form.get('image')
            session.add(mooc)
            session.commit()
            flash('MOOC {} Successfully Edited'.format(mooc.title))
            return redirect(url_for('mooc.show_moocs', field_id=field_id))

        return render_template('edit_mooc.html', mooc=mooc, field=field)
    else:
        return jsonify(error={'msg': "You are not the owner of that!!"}), 401
Ejemplo n.º 2
0
def init_all():
    logger.info(
        "[AccountInit] all account which is UPDATING has changed into NOT_INIT"
    )
    session.query(Account).filter(Account.update_status != AccountStatus.RESET)\
        .update({Account.update_status: AccountStatus.NOT_INIT})
    session.commit()
Ejemplo n.º 3
0
    def insert_user(user_id, password, name):

        user = UserModel(user_id, password, name)

        session.add(user)
        session.commit()
        session.close()
Ejemplo n.º 4
0
def signup(ctx, args_str):
    """Sign up for an event."""

    user = ctx.message.author
    args = args_str.split(DELIMITER)
    print(args)
    eid = args[0]
    if (len(args) == 2):
        print("2")
        m_status = args[1]
    else:
        m_status = 1

    db_user = session.query(MeetupUser).filter_by(userid=user.id,
                                                  event_id=eid).first()
    if db_user:
        print("if:" + str(db_user.id))
        m_user = db_user
        m_user.status = m_status
    else:
        m_user = MeetupUser(userid=user.id, event_id=eid, status=m_status)

    m_event = session.query(MeetupEvent).filter_by(id=eid).first()
    if not m_event:
        return "No event found with ID " + eid

    session.add(m_user)
    session.commit()

    retstring = "<@" + user.id + "> signed up for event ["
    retstring += str(m_event.id) + "]: \n"
    retstring += "Status: " + str(m_user.status)

    return retstring
Ejemplo n.º 5
0
    def insert_friend(owner_user_id, other_user_id):
        friendship = FriendModel(user_id=owner_user_id, friend_user_id=other_user_id)
        additional_friendship = FriendModel(user_id=other_user_id, friend_user_id=owner_user_id)

        session.add(friendship)
        session.add(additional_friendship)
        session.commit()
Ejemplo n.º 6
0
def create_data():
    """ creates the necessary base data for workshop demo """

    # create test_user
    user = userStore.create_user('John Doe', '*****@*****.**', 'test_user', 'user123', activated='True')
    print('created test user: {}'.format(user))

    # load csv's into SQLite
    breweries = os.path.join(thisDir, 'breweries.csv')
    categories = os.path.join(thisDir, 'categories.csv')
    styles = os.path.join(thisDir, 'styles.csv')

    # call our function to load data to SQLite
    load_csv(Category, categories)
    load_csv(Style, styles)
    load_csv(Brewery, breweries, created_by=user.id)

    # find mankato brewrey and load beers from json file
    mankatoBrewery = session.query(Brewery).filter(Brewery.name == 'Mankato Brewery').first()
    for beer, photoBlob in get_mankato_beers():
        # create new beer first
        photo_name = beer.photo_name
        del beer.photo_name

        # add created by
        beer['created_by'] = user.id
        newBeer = Beer(**beer)

        # create new beer photo
        # newBeer.photos.append(create_beer_photo(beer_id=newBeer.id, photo_name=photo_name, data=photoBlob))
        newBeer.photos.append(BeerPhotos(**create_beer_photo(photo_name, photoBlob)))
        mankatoBrewery.beers.append(newBeer)

    # commit db changes
    session.commit()
Ejemplo n.º 7
0
def updateLink(request):
    reqJson = requestBody(request)
    resJson = {"flag": "error", "msg": "数据更新失败"}
    l_id = reqJson.get("l_id")
    l_title = reqJson.get("title")
    l_url = reqJson.get("url")
    l_tag = reqJson.get("tags")
    l_desc = reqJson.get("desc")
    l_rate = reqJson.get("rate")
    l_userid = reqJson.get("userid")
    if l_id == None or l_id == "":
        resJson['msg'] = "数据ID不存在"
        return resJson
    if l_userid == None or l_userid == "":
        resJson['msg'] = "用户标识ID不存在"
        return resJson
    try:
        queryLink = session.query(CLink).filter(CLink.id == l_id).all()
        if len(queryLink) != 0:
            queryLink[0].l_title = l_title
            queryLink[0].l_url = l_url
            queryLink[0].l_tag = l_tag
            queryLink[0].l_desc = l_desc
            queryLink[0].l_rate = l_rate
            session.commit()
            resJson["flag"] = "success"
            resJson["msg"] = "数据更新成功"
    except exc.InvalidRequestError:
        session.rollback()
        resJson["msg"] = "数据更新失败"
    except Exception as e:
        print(str(type(e)))
        resJson['msg'] = repr(e)
        session.rollback()
    return resJson
Ejemplo n.º 8
0
    def create_tool(self):
        # validate the data
        validators = True

        all_inputs = [
            self.name_input.get(),
            self.description_input.get('1.0', END),
            self.daily_price_input.get(),
            self.half_day_price_input.get(),
            self.delivery_price_input.get()
        ]

        for field in all_inputs:
            if field == "":
                self.error_label.config(text="Please fill all fields")
                validators = False

        if validators:
            new_tool = Tools()
            new_tool.name = self.name_input.get()
            new_tool.description = self.description_input.get('1.0', END)
            new_tool.daily_price = self.daily_price_input.get()
            new_tool.half_day_price = self.half_day_price_input.get()
            new_tool.delivery_cost = self.delivery_price_input.get()
            new_tool.owner_id = self.CURRENT_USER
            new_tool.availability = True

            session.add(new_tool)
            session.commit()

            self.error_label.config(text="New tool successfully added",
                                    fg="green")
Ejemplo n.º 9
0
def addLink(request):
    reqJson = requestBody(request)
    resJson = {"flag": "error", "msg": "数据新增失败"}
    l_title = reqJson.get("title")
    l_url = reqJson.get("url")
    l_tag = reqJson.get("tags")
    l_desc = reqJson.get("desc")
    l_rate = reqJson.get("rate")
    l_userid = reqJson.get("userid")
    if l_userid == None or l_userid == "":
        resJson['msg'] = "用户标识ID不存在"
        return resJson
    try:
        link = CLink(l_title, l_url, l_tag, l_desc, l_rate, l_userid)
        session.add(link)
        session.commit()
    except exc.InvalidRequestError:
        session.rollback()
    except Exception as e:
        print(str(type(e)))
        resJson['msg'] = repr(e)
        session.rollback()
    resJson["flag"] = "success"
    resJson["msg"] = "数据新增成功"
    return resJson
Ejemplo n.º 10
0
def meetup(ctx, args_str):
    """Creates an event for people to sign up to.

    At least that is the plan."""
    print("Bla!" + args_str)
    if not args_str:
        print("empty string")
        return show_meetups()

    args_str = args_str.replace("; ", ";")
    print("check:" + args_str)

    user = ctx.message.author
    date, title, event_descr = args_str.split(DELIMITER)

    event_date = datetime.strptime(date, "%d.%m.%Y %H:%M")
    m_event = MeetupEvent(date=event_date,
                          title=title,
                          description=event_descr,
                          created_by=str(user.id))
    session.add(m_event)
    session.commit()

    retstring = "**<@" + user.id + "> created an Event:**" + "\n"
    retstring += "Date: " + m_event.date.strftime("%d.%m.%Y") + "\n"
    retstring += "Time: " + m_event.date.strftime("%H:%M") + "\n"
    retstring += "Title: **" + m_event.title + "**\n"
    retstring += "Description: " + m_event.description + "\n"
    retstring += "--------------" + "\n"
    retstring += "You can sign up for this event by typing *'!signup "
    retstring += str(m_event.id) + "'*."

    return retstring
Ejemplo n.º 11
0
    def test_follow(self):
        u1 = Users()
        u1.username = '******'
        u1.password = '******'
        u1.nickname = 'Json'
        u1.description = 'This is Json'
        u1.email = '*****@*****.**'
        u1.imgpath = 'default.jpg'
        u1.last_seen = datetime.utcnow()

        u2 = Users()
        u2.username = '******'
        u2.password = '******'
        u2.nickname = 'Kathy'
        u2.description = 'This is Kathy'
        u2.email = '*****@*****.**'
        u2.imgpath = 'default.jpg'
        u2.last_seen = datetime.utcnow()

        session.add(u1)
        session.add(u2)
        session.commit()

        self.assertNotEqual(u1.unfollow(u2), None)

        u = u1.follow(u2)
        print(u1)
        print(u2)
        print(u)
        session.add(u)
        session.commit()

        self.assertEqual(u1.is_following(u2), True)
        self.assertEqual(u1.followed.count(), 1)
        self.assertEqual(u2.followed.count(), 0)
Ejemplo n.º 12
0
 def create(self, request):
     serializer = self.serializer_class(data=request.data)
     if serializer.is_valid():
         serializer.save()
         session.commit()
         return JsonResponse(serializer.data, safe=False)
     else:
         return JsonResponse(serializer.errors)
Ejemplo n.º 13
0
    def delete_item(self):
        id = self.treeview.item(self.treeview.selection(), "text")

        session.delete(session.query(Checkout).filter_by(id=id).first())
        session.commit()

        self.treeview.delete(*self.treeview.get_children())
        self.loadTable()
Ejemplo n.º 14
0
    def insert_message(user_id, room_id, content, type):
        message = MessageModel(user_id=user_id,
                               room_id=room_id,
                               content=content,
                               type=type)

        session.add(message)
        session.commit()
Ejemplo n.º 15
0
def insert_room():
    room = Room(name="")

    session.add(room)
    session.commit()

    room_id = session.query(Room.id).first()
    return room_id
Ejemplo n.º 16
0
def update_profile(user_id, user_data):
    user = session.query(User).filter(User.id == user_id).first()

    user.name = user_data['name'] if user_data['name'] else user.name
    user.img = user_data['img'] if user_data['img'] else user.img
    user.introduction = user_data['status_message'] if user_data[
        'status_message'] else user.introduction

    session.commit()
Ejemplo n.º 17
0
def create_user(login_session):
    """Create a new user when logged in by oauth2 and Return user id"""
    new_user = User(name=login_session['username'],
                    email=login_session['email'],
                    picture=login_session['picture'])
    session.add(new_user)
    session.commit()
    user = session.query(User).filter_by(email=login_session['email']).one()
    return user.id
Ejemplo n.º 18
0
 def addpost(self, user_id, nickname, post_body):
     post = Posts()
     post.user_id = user_id
     post.body = post_body
     post.timestamp = datetime.utcnow()
     session.add(post)
     session.commit()
     # 建立全文检索索引
     create_index(user_id=user_id, post_id=post.id, nickname=nickname, post_body=post_body)
     return post
Ejemplo n.º 19
0
def insert(uid):
    try:
        query = session.query(User).filter(User.uid == uid).first()
        logging.error('exists '+str(query.uid))
        return 'exists'
    except AttributeError:
        session.add(User(uid,0,0,1,0,'0',0,0,0,0,datetime.datetime.now().date(),'',0,0,0,0))
        session.commit()
        logging.error('ok')
        return 'ok'
Ejemplo n.º 20
0
    def return_tool(self):
        if self.feedback.get('1.0', END) == "":
            self.error_label.config(text="Please fill all fields")
        return_tool = Returns(returned=True, booking_id=self.booking_id,
                              tool_condition=self.feedback.get('1.0', END), date=str(date.today()))

        session.add(return_tool)
        session.commit()

        self.error_label.config(text="Item returned successfully")
Ejemplo n.º 21
0
def insert_user(user_id, user_password, user_name):

    user = User(id=user_id,
                password=user_password,
                name=user_name,
                img=UserDefaultValue.image,
                introduction=UserDefaultValue.introduction)

    session.add(user)
    session.commit()
    session.close()
Ejemplo n.º 22
0
    async def delete(self, instance_id: str):
        post = session.query(Post).filter(Post.id == instance_id).first()

        if not post:
            raise HTTPNotFound(text="Post {} doesn't exist".format(id),
                               content_type="application/text")

        session.delete(post)
        session.commit()

        return Response(status=204)
Ejemplo n.º 23
0
    def book_tool(self):
        validators = {"days": False, "availability": True}

        # validation
        if self.how_many_days.get() == 0:
            self.validation_label.config(
                text="You have to select a period of time for your booking")
            validators['days'] = False
        else:
            validators["days"] = False

        # check the availability of the tool
        # grab all the bookings for the selected tool
        _bookings = session.query(Booking).filter(
            Booking.tool_id == self.tool_id).all()

        already_booked = False
        for booking in _bookings:
            their_booking_day = booking.booked_date
            their_period_of_time = booking.duration_of_booking
            their_deltatime = datetime.datetime.strptime(their_booking_day, '%Y-%m-%d') +\
                              datetime.timedelta(days=float(their_period_of_time))

            my_booking_day = datetime.datetime.combine(
                self.calendar.get_date(), datetime.time.min)
            my_period_of_time = self.period_of_time.get()
            my_deltatime = my_booking_day + datetime.timedelta(
                days=float(my_period_of_time))

            if their_deltatime > my_booking_day:
                # the tool is booked in that daterange
                self.validation_label.config(
                    text=f"Somebody booked that tool in that daterange "
                    f"{their_booking_day} - {their_deltatime}")
                break
            else:
                validators["days"] = True

        if validators['days'] == True and validators["availability"] == True:
            order = Checkout()
            order.user_id = self.CURRENT_USER
            order.tool_id = self.tool_id
            order.duration_of_booking = self.how_many_days.get()
            order.booked_date = self.calendar.get_date()

            if self.delivery.get() == 1:
                order.delivery = True
            else:
                order.delivery = False

            session.add(order)
            session.commit()

            self.validation_label.config(text="Item added to basked")
Ejemplo n.º 24
0
def add():
    uid = int(request.args.get('user_id'))
    refer = str(request.args.get('refer'))

    try:
        query = session.query(User).filter(User.uid == uid).first()
        logging.error(query.timezone)
        return 'exists'
    except AttributeError:
        session.add(User(uid,0,15,1,0,refer,0,0,0,0,datetime.datetime.now().date(),'',0,0,0,0))
        session.commit()
    return 'ok'
Ejemplo n.º 25
0
def new_field():
    """Add a new CS field"""
    if request.method == 'POST':
        if request.form.get('name'):
            field = Field(name=request.form.get('name'),
                          user_id=login_session.get('user_id'))
            session.add(field)
            session.commit()
            flash('New Field {} Successfully Created'.format(field.name))
        return redirect(url_for('field.index'))

    return render_template('new_field.html')
Ejemplo n.º 26
0
 def create(self, request):
     eligbl_id = request.data.pop('eligbl_id')
     eligbl_se = LenderEligblSerializer(data=eligbl_id)
     eligbl_se.is_valid()
     eligbl_se.save()
     data = request.data
     data['eligbl_id'] = eligbl_se.data
     serializer = self.serializer_class(data=data)
     if serializer.is_valid():
         serializer.save()
         session.commit()
         return JsonResponse(serializer.data, safe=False)
     else:
         return JsonResponse(serializer.errors)
Ejemplo n.º 27
0
def create_user(email, password, first_name, last_name):
    """
    Create a new user

    :param email: String
    :param password: String
    :param first_name: String
    :param last_name: String
    :return object:
    """
    user = User(email=email, first_name=first_name, last_name=last_name)
    user.hash_password(password)
    session.add(user)
    session.commit()
    return user
Ejemplo n.º 28
0
    async def patch(self, request: Request, instance_id: str):

        data = await request.json()

        post = session.query(Post).filter(Post.id == instance_id).first()
        post.title = data['title']
        post.body = data['body']
        post.created_at = data['created_at']
        post.created_by = data['created_by']

        session.commit()

        return Response(status=201,
                        body=self.resource.render_and_encode(post),
                        content_type='application/json')
Ejemplo n.º 29
0
def position(terminal_request):
    # Load the field which your need to save!
    content = terminal_request['client_content']
    # Do some Resolution according your need!
    position_instance = PositionSplit(content)
    # Get the attribute of the PositionSplit and you'll got a Dict type
    result_dict = position_instance.result
    # Convert the client request data to the new type if you need!
    ConvertBaseRegister(result_dict)
    # Get the data with Dict format!
    position_info = position_instance.result
    print 'position_info', position_info
    # Send to ORM & Save it to Data Base!
    p_i = PositionTable(**position_info)
    session.add(p_i)
    session.commit()
Ejemplo n.º 30
0
def position(terminal_request):
    # Load the field which your need to save!
    content = terminal_request["client_content"]
    # Do some Resolution according your need!
    position_instance = PositionSplit(content)
    # Get the attribute of the PositionSplit and you'll got a Dict type
    result_dict = position_instance.result
    # Convert the client request data to the new type if you need!
    ConvertBaseRegister(result_dict)
    # Get the data with Dict format!
    position_info = position_instance.result
    print "position_info", position_info
    # Send to ORM & Save it to Data Base!
    p_i = PositionTable(**position_info)
    session.add(p_i)
    session.commit()
Ejemplo n.º 31
0
    def checkout_items(self):
        print('hit')
        user_items = session.query(Checkout).filter(
            Checkout.user_id == self.CURRENT_USER.id)
        for item in user_items:
            new_booking = Booking(booked_date=item.booked_date,
                                  duration_of_booking=item.duration_of_booking,
                                  tool_id=item.tool_id,
                                  user_id=item.user_id,
                                  delivery=item.delivery)
            session.add(new_booking)

            session.delete(item)
            session.commit()

        self.treeview.delete(*self.treeview.get_children())
        self.loadTable()
Ejemplo n.º 32
0
def get_available_account():
    # 最近更新的忽略掉
    all_open = get_all_open_spider()
    if len(all_open) == 0:
        return

    deadline = datetime.now() - timedelta(minutes=settings.FETCH_TIMEDELTA)
    cur_account = session.query(Account)\
        .filter(Account.oj_name.in_(all_open))\
        .filter(~Account.status.in_([AccountStatus.QUEUE,
                                     AccountStatus.STOP,
                                     AccountStatus.UPDATING,
                                     AccountStatus.ACCOUNT_ERROR]))\
        .filter(Account.updated_at < deadline)\
        .order_by(Account.updated_at.asc())\
        .with_for_update(nowait=True)\
        .first()
    if not cur_account:
        session.commit()
        return

    cur_account.set_status(AccountStatus.QUEUE)
    cur_account.save()
    return cur_account
Ejemplo n.º 33
0
 def save(self):
     self.updated_at = datetime.now()
     session.add(self)
     session.commit()
Ejemplo n.º 34
0
def init_all():
    logger.info("[AccountInit] 所有非 [NOT_INIT, STOP] 账号已经重置为 NORMAL")
    session.query(Account)\
        .filter(~Account.status.in_([AccountStatus.NOT_INIT, AccountStatus.STOP]))\
        .update({Account.status: AccountStatus.NORMAL}, synchronize_session=False)
    session.commit()