Example #1
0
def editCategory(category_id):
    """Given a category id, display a form for editing the data
    describing that category, and handle the submission of that form.

    Args:
      category_id: The id of the category to be edited.

    Returns:
      Redirect to main dashboard on successful form submission, which will show
      the edited category changes. Otherwise, returns rendered edit
      category template.
    """
    if 'username' not in user_session:
        return redirect('/login')
    category = session.query(Category).filter_by(id=category_id).one()
    if category.user_id != user_session['user_id']:
        return "<script>function showAuthAlert() {alert('You are not " \
             + "authorized to edit this category.');}" \
             + "</script><body onload='showAuthAlert()'>"
    original_name = category.name
    if request.method == 'POST':
        if request.form['name']:
            category.name = request.form['name']
        if request.form['description']:
            category.description = request.form['description']
        session.add(category)
        try:
            session.commit()
        except:
            session.rollback()
        flash("Category: " + original_name + " was successfully edited!")
        return redirect(url_for('showDashboard'))
    else:
        return render_template('edit_category.html', category=category)
def budget_category(budget: Budget, month, year) -> Category:
    all_categories = get_budget_categories(budget)
    choice = input("Pick category's ID which you want to budget for this month: ")
    selected_category = next((category for category in all_categories if category.id == int(choice)), None)
    if selected_category:
        new_budget_amount = input("What amount do you wish to budget for this category: ")
        category_budget = session.query(CategoryBudget) \
            .filter(
            CategoryBudget.category_id == selected_category.id,
            CategoryBudget.datetime >= datetime(year, month, 1),
            CategoryBudget.datetime <= datetime(year, month, monthrange(year, month)[1])
        ).first()

        if category_budget:
            category_budget.budgeted_amount = new_budget_amount
            session.add(category_budget)
            session.commit()

        else:
            category_budget = CategoryBudget(budgeted_amount=new_budget_amount, category_id=selected_category.id,
                                             datetime=datetime(year, month, 1))
            session.add(category_budget)
            session.commit()
    else:
        print("Incorrect category!")
Example #3
0
    def send(self, cutoff=None):
        ''' Sends this PriceRequest to the AlphaVantage API
        '''
        if self.sent:
            # Only send a request once
            print("Request %s already sent" % self.id)
            return

        # Send request:
        print("Sending Price Request %s" % self)
        result = self._send()

        # Read in result:
        if result.get('Information'):
            # An Error Occurred, Request Unscuccessful
            print("Price Request %s Unsuccessful: %s" %
                  (self.id, result['Information']))
            self.meta = result['Information']
            self.successful = False
            session.commit()
            return

        # Save the Request Meta Data:
        self.meta = json.dumps(result.get('Meta Data'))
        self.successful = True
        session.commit()

        # Read in the data:
        self.readin_data(result.get('Time Series (1min)'))
Example #4
0
def deleteTask(category_id, task_id):
    """Given a category id and task id, render a button that will allow the
    given task to be deleted, and process the clicking of that button.

    Args:
      category_id: The id of the category to be displayed after task deletion.
      task_id: The id of the task to be deleted

    Returns:
      Redirect for category that contained the deleted task on form submission,
      otherwise renders the task deletion template for display.
    """
    if 'username' not in user_session:
        return redirect('/login')
    task = session.query(Task).filter_by(id=task_id).one()
    if task.user_id != user_session['user_id']:
        return "<script>function showAuthAlert() {alert('You are not " \
             + "authorized to delete this task.');}" \
             + "</script><body onload='showAuthAlert()'>"
    if request.method == 'POST':
        session.delete(task)
        try:
            session.commit()
        except:
            session.rollback()
        flash("Task: " + task.name + " was successfully deleted!")
        return redirect(url_for('showCategory', category_id=category_id))
    else:
        return render_template('delete_task.html', task=task)
Example #5
0
def newTask(category_id):
    """Given a category id, create a new task to be tied under the
    given category.

    Args:
      category_id: The id of the category to be tied to the task.

    Returns:
      Returns redirect to category template with the category containing the
      newly created task if the form is submitted, otherwise returns the
      rendered task creation form.
    """
    if 'username' not in user_session:
        return redirect('/login')
    if request.method == 'POST':
        task = Task(name=request.form['name'],
                    description=request.form['description'],
                    category_id=category_id,
                    user_id=user_session['user_id'],
                    hours=request.form['hours'],
                    importance=request.form['importance'])
        session.add(task)
        try:
            session.commit()
        except:
            session.rollback()
        flash("Task: " + request.form['name'] + " was successfully added!")
        return redirect(url_for('showCategory', category_id=category_id))
    else:
        return render_template('create_task.html', category_id=category_id)
Example #6
0
    def delete(self):
        account = g.account

        session.delete(account)
        session.commit()

        return ('', 204)
Example #7
0
    def put(self, account_id):
        account_json = request.get_json()
        account = session.query(Account).filter(
            Account.id == account_id).first()

        if account:
            account.updated_at = datetime.datetime.utcnow()

            if 'email' in account_json:
                account.email = account_json['email']

            if 'first_name' in account_json:
                account.first_name = account_json['first_name']

            if 'last_name' in account_json:
                account.last_name = account_json['last_name']

            session.commit()

            if 'email_token' in account_json:
                if not self.link_card(account, account_json['email_token']):
                    return ('Invalid Email Token', 400)

            return jsonify(account.to_json())
        else:
            return ('Account Not Found', 404)
Example #8
0
def edit_item(category_name, item_name):
    data = request.get_json()
    item = session.query(Item).filter_by(name=item_name).one()
    user_jwt = request.headers.get('Authorization')
    # If user is not logged in or user is not in db return error response
    if user_jwt == u"null" or not verify_jwt(user_jwt):
        return create_message_response('Unauthorized access', 400)
    else:
        user_info = jwt.decode(user_jwt, SECRET, algorithms=['HS256'])
        # Check if request has required content
        if 'name' not in data or 'description' not in data:
            return create_message_response('Invalid input', 400)
        # Logged in user must match item creator to edit item
        if user_info['username'] == item.creator:
            # Use Marshmallow to create item object
            input_dict = {
                'name': data['name'],
                'description': data['description'],
                'category_name': item.category_name,
                'creator': item.creator,
            }
            item_mm = verify_item(input_dict)
            # If errors exist on object, one of the input fields is empty
            if item_mm.errors:
                return create_message_response('Input cannot be empty', 400)
            # Edit item information and commit changes
            else:
                item.name = item_mm.data.name
                item.description = item_mm.data.description
                session.add(item)
                session.commit()
                return create_message_response('Item successfully edited', 200)
            # If user is not logged in user is not item creator
        else:
            return create_message_response('Unauthorized access', 400)
def create_account() -> User:
    # Prompt user for username
    username = input("Choose your username: "******"\nHmm, that username is already taken. Let's try something different!"
        )
        username = input("Choose your username: "******"Great, choose your password now: ")
    salt = os.urandom(32)  # A new salt for this user
    key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000)

    user = User(name=username, salt=salt, key=key)
    session.add(user)
    session.commit()

    user_instance = session.query(User).filter_by(name=username).first()
    print("\nYou've successfully created the account!")

    return user_instance
Example #10
0
def add_budget(user: User) -> Budget:
    budget_name = input("Name of the new budget: ")
    budget = Budget(name=budget_name, user_id=user.id)
    session.add(budget)
    session.commit()
    new_budget = session.query(Budget).order_by(Budget.id.desc()).first()
    return new_budget
Example #11
0
    def readin_data(self, data):
        # Loop through data points
        prices = []
        for time in list(data.keys()):
            # Create new Price record
            open = data[time].get('1. open')
            high = data[time].get('2. high')
            low = data[time].get('3. low')
            close = data[time].get('4. close')
            volume = data[time].get('5. volume')
            prices.append(
                Price(
                    request_id=self.id,
                    time=datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S'),
                    open=float(open) if open else None,
                    high=float(high) if high else None,
                    low=float(low) if low else None,
                    volume=int(volume) if volume else None,
                    close=float(close),
                ))

        # Try bulk insert into database
        try:
            session.bulk_save_objects(prices)
        except:
            print("Couldn't save price request %s data:" % self.id)
            print(traceback.format_exc())
            session.rollback()

            # Mark as unsuccessful
            self.successful = False
            session.commit()
Example #12
0
    def readin_data(self, data, cutoff=None):
        # Loop through data points
        values = []
        for timestamp, rawdata in data.iteritems():
            try:
                # We sometimes get a weird ' hh:mm:ss' appended to the string, so
                # here we make sure that that is removed from the parsed date string:
                timestamp = timestamp.split(' ')[0]
                date = datetime.datetime.strptime(timestamp, '%Y-%m-%d').date()
                if cutoff and date < cutoff:
                    continue
                value = TechnicalIndicatorValue(request_id=self.id,
                                                date=date,
                                                values=json.dumps(rawdata))
                values.append(value)

            except Exception as e:
                raise e
                print("Invalid Data Point, Skipping (%s: %s)" %
                      (timestamp, rawdata))
                continue

        # Try bulk insert into database
        try:
            session.bulk_save_objects(values)
            session.commit()
        except:
            print("Couldn't save technical request %s data:" % self.id)
            print(traceback.format_exc())
            session.rollback()

            # Mark as unsuccessful
            self.successful = False
            session.commit()
Example #13
0
def deleteCategory(category_id):
    """Given a category id, display a button for deleting that category,
    and handle the clicking of that button.

    Args:
      category_id: The id of the category to be deleted

    Returns:
      Redirect to main dashboard on successful form submission, which will show
      the remaining categories. Otherwise, returns rendered delete
      category template.
    """
    if 'username' not in user_session:
        return redirect('/login')
    category = session.query(Category).filter_by(id=category_id).one()
    if category.user_id != user_session['user_id']:
        return "<script>function showAuthAlert() {alert('You are not " \
             + "authorized to delete this category.');}" \
             + "</script><body onload='showAuthAlert()'>"
    if request.method == 'POST':
        session.delete(category)
        try:
            session.commit()
        except:
            session.rollback()
        flash("Category: " + category.name + " was successfully deleted!")
        return redirect(url_for('showDashboard'))
    else:
        return render_template('delete_category.html', category=category)
Example #14
0
 def on_post(self, req, resp, *args, **kwargs):
     uid = req.context['doc']['User']
     users = session.query(User).filter(User.id == int(uid)).one()
     cid_list = req.context['doc']['Car']
     for cid in cid_list:
         user = session.query(Car).filter(Car.id == int(cid)).one()
         users.cars.append(user)
     session.commit()
Example #15
0
def createUser(user_session):
    newUser = User(name=user_session['username'],
                   email=user_session['email'],
                   image=user_session['picture'])
    session.add(newUser)
    session.commit()
    user = session.query(User).filter_by(email=user_session['email']).one()
    return user.id
Example #16
0
 def on_post(self, req, resp, *args, **kwargs):
     cid = req.context['doc']['Car']
     cars = session.query(Car).filter(Car.id == int(cid)).one()
     uid_list = req.context['doc']['User']
     for uid in uid_list:
         car = session.query(User).filter(User.id == int(uid)).one()
         cars.users.remove(car)
     session.commit()
Example #17
0
 def _send(self):
     if self.sent:
         return
     else:
         self.sent = True
         self.time_sent = datetime.datetime.now()
         session.commit()
         return requests.get(self.url).json()
Example #18
0
def add_parent_category(budget: Budget) -> ParentCategory:
    parent_category_name = input("The name of the new parent category: ")
    parent_category = ParentCategory(name=parent_category_name,
                                     budget_id=budget.id)
    session.add(parent_category)
    session.commit()
    new_parent_category = session.query(Budget).order_by(
        Budget.id.desc()).first()
    return new_parent_category
Example #19
0
 def find_or_create_product_group(self, amazon_name):
     product_group = session.query(ProductGroup).filter_by(
         amazon_name=amazon_name).first()
     if not product_group:
         product_group = ProductGroup(amazon_name=amazon_name,
                                      name=amazon_name)
         session.add(product_group)
         session.commit()
     return product_group
Example #20
0
def update():
    users = session.query(User).all()
    users.reverse()

    for user in users:
        if user.qq == "7420838":
            break
        user.send = False
    session.commit()
Example #21
0
 def link_card(self, account, email_token):
     card = session.query(Card).filter(
         Card.email_token == email_token).first()
     if card and account.email == card.email:
         card.account = account
         session.commit()
         return True
     else:
         return False
Example #22
0
def add():
    df = pd.read_csv('qq.csv')
    for qq in df['qq']:
        newqq = str(qq)
        users = session.query(User).filter(User.qq == newqq).all()
        if len(users) == 0:
            user = User(name="", qq=newqq, send=False)
            session.add(user)
    session.commit()
Example #23
0
    def delete(self, keg_id):
        keg = session.query(Keg).filter(Keg.id == keg_id).first()

        if keg:
            session.delete(keg)
            session.commit()

            return ('', 204)
        else:
            return ('Keg Not Found', 404)
Example #24
0
 def find_or_create_subsite(self, subreddit_name):
     reddit = session.query(Site).filter_by(name="Reddit").first()
     subsite = session.query(Subsite).filter_by(
         site_id=reddit.id, name=subreddit_name).first()
     if not subsite:
         url = self.BASE_URL + "/r/" + subreddit_name
         subsite = Subsite(name=subreddit_name, site_id=reddit.id, url=url)
         session.add(subsite)
         session.commit()
     return subsite
def delete_category(category_name):
    user_jwt = request.headers.get('Authorization')
    # If user is not logged in or user is not in db return error response
    if user_jwt == u"null" or not verify_jwt(user_jwt):
        create_message_response('Unauthorized access', 400)
    else:
        del_cat = session.query(Category).filter_by(name=category_name).one()
        session.delete(del_cat)
        session.commit()
        return create_message_response('Category successfully deleted!', 200)
Example #26
0
    def delete(self, beer_id):
        beer = session.query(Beer).filter(Beer.id == beer_id).first()

        if beer:
            session.delete(beer)
            session.commit()

            return ('', 204)
        else:
            return ('Beer Not Found', 404)
Example #27
0
    def delete(self, account_id):
        account = session.query(Account).filter(
            Account.id == account_id).first()

        if account:
            session.delete(account)
            session.commit()

            return ('', 204)
        else:
            return ('Account Not Found', 404)
Example #28
0
    def post(self):
        beer_json = request.get_json()

        try:
            beer = Beer(name=beer_json['name'], description=beer_json['description'])
            session.add(beer)
            session.commit()

            return (jsonify(beer.to_json()), 201)
        except Exception as e:
            return ('Missing Parameters', 400)
Example #29
0
def reactconnect():
    data = request.get_json()
    access_token = data['access_token']
    # If access token not sent in request, return error response
    if not access_token:
        response = make_response(json.dumps('No access token present'), 400)
        response.headers['Content-Type'] = 'application/json'
        return response
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # If there was an error in the access token info, abort
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user
    gplus_id = data['token_id']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Get user info
    email = data['email']
    user_id = get_user_id(email)
    if not user_id:
        input_dict = {
            'name': data['name'],
            'email': data['email'],
            'picture': data['picture']
        }
        user = verify_user(input_dict)
        session.add(user.data)
        session.commit()

    # Make JWT with users username
    user_jwt = jwt.encode({'username': email}, SECRET, algorithm='HS256')
    data = {'jwt': user_jwt}
    response = make_response(json.dumps(data), 200)
    response.headers['Content-Type'] = 'application/json'
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
Example #30
0
def rename_budget(user: User) -> Budget:
    display_budgets(user)
    choice = input("Pick budget's ID to rename: ")

    selected_budget = next((budget for budget in user.budgets if budget.id == int(choice)), None)
    if selected_budget:
        new_name = input(f"Provide new name for {selected_budget.name}: ")
        selected_budget.name = new_name
        session.add(selected_budget)
        session.commit()
        return selected_budget
    else:
        print("Incorrect budget!")
def insertar_anuncio(ad: dict):
    anuncio = obtener_anuncio(ad)
    timestamp = int(ad['list_time']['value'])
    anuncio.publicado = str(dt.date.fromtimestamp(timestamp))

    session.add(anuncio)
    session.flush()

    for imagen in obtener_imagenes(ad):
        imagen.anuncio_id = anuncio.id
        session.add(imagen)

    session.commit()
Example #32
0
    def on_post(self, req, resp, *args, **kwargs):
        uid = req.context['doc']['User']
        user = session.query(User).filter(User.id == int(uid)).one()
        cid_list = req.context['doc']['Car']
        for cid in cid_list:
            try:
                with session.begin_nested():
                    car = session.query(Car).filter(Car.id == int(cid)).one()
                    user.cars.append(car)
            except Exception as e:
                raise falcon.HTTPBadRequest("User:%s" % uid,
                                            "is linking with Car: %s" % cid)

        session.commit()
def rename_category(budget: Budget) -> Category:
    all_categories = get_budget_categories(budget)
    display_categories(budget)
    choice = input("Pick category's ID to rename: ")

    selected_category = next((category for category in all_categories if category.id == int(choice)), None)
    if selected_category:
        new_name = input(f"Provide new name for {selected_category.name}: ")
        selected_category.name = new_name
        session.add(selected_category)
        session.commit()
        return selected_category
    else:
        print("Incorrect category!")
def add_category() -> Category:
    category_name = input("The name of the new category: ")
    parent_id = int(input("To which parent category does it belong (parent_id): "))
    new_budgeted_amount = float(input("Write budgeted amount: "))
    category = Category(name=category_name, parent_id=parent_id)
    session.add(category)
    session.commit()
    # TODO: If more than one person creates a new category at the same time we might get incorrect data here
    new_category = session.query(Category).order_by(Category.id.desc()).first()
    category_budget = CategoryBudget(budgeted_amount=new_budgeted_amount, category_id=new_category.id,
                                     datetime=datetime.now())
    session.add(category_budget)
    session.commit()
    return new_category
Example #35
0
    def post(self):
        account_json = request.get_json()
        try:
            hashed_pwd = bcrypt.hashpw(str(account_json['password']),
                                       bcrypt.gensalt())
            account = Account(email=account_json['email'],
                              first_name=account_json['first_name'],
                              last_name=account_json['last_name'],
                              password=hashed_pwd)

            session.add(account)
            session.commit()
            return (jsonify(account.to_json()), 201)
        except Exception as e:
            return ('Missing parameters: %s' % (e), 400)
def upload_events():
    """Attempts to parse and store a JSON file sent in the request.
        Every file uploaded is considered as an input set, which is a set of data
        that provides a complete test case for the app's main functionality.
        
    Returns:
      The dashboard page state with message flashes on error.
    """
    if request.method == 'POST':
        file = request.files['file']
        if file and valid_file(file.filename):
            try:
               events = json.load(file)
            except:
                flash("An error occurred while parsing the provided JSON. Please check the validity of the data.")
                return redirect(url_for('show_dashboard'))


            try:
                input_set = InputSet(name=request.form["name"])
                session.add(input_set)

                for event in events:
                    event_type = session.query(EventType).filter_by(name=event["type"]).one()
                    
                    # Ensure that start and endtimes are stored as timestamps
                    # with no corresponding date.
                    start_time = datetime.strptime(event["startTime"], "%H:%M:%S").time()
                    end_time = datetime.strptime(event["endTime"], "%H:%M:%S").time()
                    
                    db_event = Event(title=event["title"], description=event["description"], 
                                    start_time=start_time, end_time=end_time, address=event["address"], 
                                    type_id=event_type.id, input_set_id=input_set.id)

                    session.add(db_event)

                session.commit()
            except:
                session.rollback()
                flash("An error occurred while saving the provided JSON. Please check the validity of the data.")
                return redirect(url_for('show_dashboard'))

            return redirect(url_for('show_dashboard'))
        else:
            flash("A JSON file was not provided. Nothing to see here...")
    return redirect(url_for('show_dashboard'))
Example #37
0
def newCategory():
    """Provides the interface with which the user adds new categories.

    Returns:
      Redirect to dashboard page on category creation, otherwise renders the
      category creation form.
    """
    if 'username' not in user_session:
        return redirect('/login')
    if request.method == 'POST':
        category = Category(name=request.form['name'],
                            description=request.form['description'],
                            user_id=user_session['user_id'])
        session.add(category)
        try:
            session.commit()
        except:
            session.rollback()
        flash("Category: " + request.form['name'] + " was successfully added!")
        return redirect(url_for('showDashboard'))
    else:
        return render_template('create_category.html')
from session import session
from database_model import Restaurant, Base, MenuItem, User

# Delete all existing
session.query(Restaurant).delete()
session.query(MenuItem).delete()
session.query(User).delete()
session.commit()

# ############  Create new ones ############

# Create dummy user
User1 = User(name="Diner Jack", email="*****@*****.**",
             picture='http://localhost:5000/static/diner-owner.jpg')
session.add(User1)
session.commit()


# Restaurant UrbanBurger
restaurant1 = Restaurant(user_id=1, name="Urban Burger")
session.add(restaurant1)
session.commit()


menuItem1 = MenuItem(
       user_id=1,
       name="French Fries",
       description="with garlic and parmesan",
       price="$2.99",
       course="Appetizers",
       restaurant=restaurant1)
Example #39
0
def commit(obj):
    session.add(obj)
    session.commit()