Exemplo n.º 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)
Exemplo n.º 2
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
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
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!")
Exemplo n.º 5
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)
Exemplo n.º 6
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)
Exemplo n.º 7
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
Exemplo n.º 8
0
 def find_or_create_comment(self, attrs):
     comment = session.query(Comment).filter_by(
         site_comment_ident=attrs['site_comment_ident']).first()
     if not comment:
         comment = Comment()
         for key in attrs:
             setattr(comment, key, attrs[key])
         session.add(comment)
     return comment
Exemplo n.º 9
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
Exemplo n.º 10
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
Exemplo n.º 11
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()
Exemplo n.º 12
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
Exemplo n.º 13
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)
Exemplo n.º 14
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
Exemplo n.º 15
0
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()
Exemplo n.º 16
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 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
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!")
Exemplo n.º 19
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)
Exemplo n.º 20
0
def rename_parent_category(budget: Budget) -> ParentCategory:
    display_parent_categories(budget)
    choice = input("Pick parent category's ID to rename: ")

    selected_parent = next(
        (parent
         for parent in budget.parent_categories if parent.id == int(choice)),
        None)
    if selected_parent:
        new_name = input(f"Provide new name for {selected_parent.name}: ")
        selected_parent.name = new_name
        session.add(selected_parent)
        session.commit()
        return selected_parent
    else:
        print("Incorrect parent category!")
Exemplo n.º 21
0
 def create_mentions(self, asin, comment_attrs):
     logging.info(comment_attrs)
     logging.info(asin)
     subsite = self.find_or_create_subsite(comment_attrs['subsite_name'])
     logging.info("Subsite: " + str(subsite))
     comment_attrs['subsite_id'] = subsite.id
     comment = self.find_or_create_comment(comment_attrs)
     product = self.find_or_create_product(asin)
     logging.info(comment)
     logging.info(product)
     if product and comment:
         mention = session.query(Mention).filter_by(
             product_id=product.id, comment_id=comment.id).first()
         if not mention:
             mention = Mention(product_id=product.id, comment_id=comment.id)
             session.add(mention)
             session.commit()
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'))
Exemplo n.º 23
0
 def find_or_create_product(self, asin, region='US'):
     product = session.query(Product).filter_by(asin=asin).first()
     logging.info(product)
     if not product:
         attrs = self.get_product_from_amazon_api(asin, region='US')
         if attrs:
             product_group = self.find_or_create_product_group(
                 attrs['product_group_string'])
             attrs['product_group_id'] = product_group.id
             attrs.pop('product_group_string')
             product = Product(asin=asin)
             for key in attrs:
                 setattr(product, key, attrs[key])
             session.add(product)
             session.commit()
         else:
             pass
     return product
def add_transaction(budget: Budget) -> bool:
    name = input("Name of the transaction: ")
    try:
        outflow = float(input("Outflow amount: ") or 0.)

        if outflow == 0.:
            inflow = float(input("Inflow amount: "))
        else:
            inflow = 0.

        category_id = int(input("Category id: "))
        valid_ids = []
        for parent in budget.parent_categories:
            for category in parent.categories:
                valid_ids.append(category.id)

        if category_id not in valid_ids:
            print("Invalid category ID!")
            return False

        provided_date = input("Date of the transaction (YYYY-MM-DD): ")

        if provided_date:
            receipt_date = datetime.strptime(provided_date, '%Y-%m-%d').date()
        else:
            receipt_date = datetime.today().date()

        payee_name = input("Name of payee/payer: ")

    except ValueError:
        print("You provided an incorrect value!")
        return False

    transaction = Transaction(name=name,
                              payee_name=payee_name,
                              amount_inflow=inflow,
                              amount_outflow=outflow,
                              category_id=category_id,
                              receipt_date=receipt_date)
    session.add(transaction)
    session.commit()
    print("The transaction has been added!")

    return True
Exemplo n.º 25
0
def put_pms_feedback():
    tstamp = datetime.now()
    req_json = json.loads(request.json)
    resp_json = {'status': 'UND', 'data': req_json, 'timestamp': tstamp}
    session.rollback()
    try:
        im_remark_id = req_json['im_remark_id']
        feedback = req_json['feedback']
        created_on = tstamp
        new_fdb = PMS_Feedback(im_remark_id, feedback, tstamp)
        session.add(new_fdb)
        session.commit()

        resp_json['status'] = 'OK'

    except Exception as e:
        resp_json['status'] = 'ERROR'
        resp_json['error'] = str(e)

    return jsonify(resp_json)
Exemplo n.º 26
0
    def do_POST(self):

        if self.path.endswith("/restaurants/new"):

            ctype, pdict = cgi.parse_header(self.headers['content-type'])
            print(ctype, pdict)
            if ctype == 'multipart/form-data':
                print(type(self.rfile), type(pdict))
                pdict['boundary'] = bytes(pdict['boundary'], 'utf-8')
                fields = cgi.parse_multipart(self.rfile, pdict)
                messagecontent = fields.get('newRestaurantName')
                newRestaurant = Restaurant(
                    name=messagecontent[0].decode("utf-8"))
                session.add(newRestaurant)
                session.commit()
                print(messagecontent)

            self.send_response(301)
            self.send_header('Content-type', 'text/html')
            self.send_header('Location', 'restaurants')
            self.end_headers()
Exemplo n.º 27
0
def add_item(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):
        return create_message_response('Unauthorized access', 400)
    else:
        # Get creator username from jwt in authorization header
        user_info = jwt.decode(user_jwt, SECRET, algorithms=['HS256'])
        creator = user_info['username']
        data = request.get_json()
        # Check if request has required content
        if 'name' not in data or 'description' not in data:
            return create_message_response('Invalid input', 400)
        # Use Marshmallow to create item object
        input_dict = {
            'name': data['name'],
            'description': data['description'],
            'category_name': category_name,
            'creator': creator
        }
        item_mm = verify_item(input_dict)
        # If errors exist in object, one of the input fields is empty
        if item_mm.errors:
            return create_message_response('input cannot be empty', 400)
        else:
            # Check if input item name already exists in db
            item_exists = session.query(Item).filter_by(
                name=data['name']).all()
            if item_exists:
                return create_message_response('Item already exists', 400)
            # If item doesn't already exist, create new item and add to db
            else:
                new_item = Item(name=data['name'],
                                description=data['desc'],
                                category_name=category_name,
                                creator=creator)
                session.add(new_item)
                session.commit()
                return create_message_response('Item successfully added!', 200)
Exemplo n.º 28
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')
Exemplo n.º 29
0
def editTask(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 edit.
      task_id: The id of the task to be edited

    Returns:
      Redirect for category that contains the edited task on form submission,
      otherwise renders the task edit 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 edit this task.');}" \
             + "</script><body onload='showAuthAlert()'>"
    original_name = task.name
    if request.method == 'POST':
        if request.form['name']:
            task.name = request.form['name']
        if request.form['description']:
            task.description = request.form['description']
        if request.form['hours']:
            task.description = request.form['hours']
        if request.form['importance']:
            task.description = request.form['importance']
        session.add(task)
        try:
            session.commit()
        except:
            session.rollback()
        flash("Task: " + original_name + " was successfully edited!")
        return redirect(url_for('showCategory', category_id=category_id))
    else:
        return render_template('edit_task.html', task=task)
Exemplo n.º 30
0
    def post(self):
        keg_json = request.get_json()

        try:
            keg = Keg(pints=keg_json['pints'],
                      starting_pints=keg_json['starting_pints'],
                      kegerator_ordinal=keg_json['kegerator_ordinal'])

            # TODO: Check for if the count will pass the kegerator max_count value and fail if so
            keg.kegerator = session.query(Kegerator).filter(
                Kegerator.id == int(keg_json['kegerator_id'])).first()
            keg.beer = session.query(Beer).filter(
                Beer.id == int(keg_json['beer_id'])).first()

            if keg.beer and keg.kegerator:
                session.add(keg)
                session.commit()
                return (jsonify(keg.to_json()), 201)
            else:
                return ('Beer or Kegerator not found', 400)
        except Exception as e:
            session.rollback()
            return ('Missing Parameters', 400)
Exemplo n.º 31
0
def add_category():
    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)
    data = request.get_json()
    # Check if request has required content
    if 'name' not in data:
        return create_message_response('Invalid request', 400)
    name = data['name']
    # If name is empty or whitespace return error
    if name.isspace() or not name:
        return create_message_response('Name cannot be empty', 400)
    else:
        # If name already exists in Category table return error
        category_exists = session.query(Category).filter_by(name=name).all()
        if category_exists:
            return create_message_response('Category already exists', 400)
        else:
            new_category = Category(name=name)
            session.add(new_category)
            session.commit()
            return create_message_response('Category successfully added!', 200)
Exemplo n.º 32
0
def commit(obj):
    session.add(obj)
    session.commit()
Exemplo n.º 33
0
                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()

    def __repr__(self):
        return '<TechnicalRequest %s: %s - %s>' % (self.id, self.tradable.name,
                                                   self.technical_indicator)


if __name__ == '__main__':

    spy = session.query(Tradable).first()
    technical = session.query(TechnicalIndicator).first()
    request = TechnicalRequest(tradable=spy, technical_indicator=technical)
    session.add(request)
    session.commit()

    request.send(cutoff=datetime.date(2018, 8, 1))
    session.commit()
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)
Exemplo n.º 35
0
    ratings = trim_ratings(ratings)

    names = driver.find_elements_by_css_selector('.memberOverlayLink .info_text > div:nth-child(1)')

    addresses = driver.find_elements_by_css_selector('.memberOverlayLink .info_text > div > strong')

    contributions = driver.find_elements_by_css_selector('.memberBadgingNoText > span:nth-child(2)')
    likes = driver.find_elements_by_css_selector('.memberBadgingNoText > span:nth-child(4)')

    for j in range(0, len(reviews)):
        rev = GansevoortReview(
            id=i * 10 + j,
            date=dates[j].get_attribute('title'),
            description=reviews[j].text,
            # address=addresses[j].text,
            rating=ratings[j],
            contributions=contributions[j].text,
            # likes=likes[j].text,
            name=names[j].text
            )
        session.add(rev)
        session.commit()

    sleep(randint(8, 15))

    requests += 1
    elapsed_time = time() - start_time
    print('Request:{}; Frequency: {} requests/s'.format(requests, requests / elapsed_time))

driver.close()
session.close()
Exemplo n.º 36
0
def add_menu_item(item):
    session.add(item)
    session.commit()
Exemplo n.º 37
0
# -*- coding: utf-8 -*-
from models import User, Image
from session import session

# UserとImageを追加する。
testuser = User('test_cascade', '', '')
testimage = Image('image name', testuser)

session.add(testuser)
session.add(testimage)
session.commit()

# 追加されているか確認
user = session.query(User).filter(User.name=='test_cascade').first()
image = session.query(Image).filter(Image.filename=='image name').first()
print user.name
print image.filename

# Userを削除する。Imageは直接削除しない。
session.delete(user)
session.commit()

# UserもImageも削除されていることを確認
user = session.query(User).filter(User.name=='test_cascade').first()
image = session.query(Image).filter(Image.filename=='image name').first()
print user
print image


Exemplo n.º 38
0
from models import User
from session import session

print len(session.query(User).all())

session.add(User('hoge','hoge','hoge'))

print len(session.query(User).all())

session.rollback()

print len(session.query(User).all())



Exemplo n.º 39
0
def add_restaurant(restaurant):
    session.add(restaurant)
    session.commit()