示例#1
0
def edit(id):
    #If the user is not logged, redirect to login
    if bookshelf.user.user_info['log'] == False:
        return redirect(url_for('user.login'))

    book = get_model().read_comic(id)

    #If the user is not the publisher, redirect to main page
    # If the user is not logged, redirect to login
    if bookshelf.user.user_info['id'] != book['publishedBy']:
        return redirect(url_for('user.login'))

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)
        data['author'] = book['author']
        data['publishedDate'] = book['publishedDate']

        book = get_model().update_comic(data, id)

        return redirect(url_for('.view', id=book['id']))

    return render_template("form.html",
                           action="Edit",
                           book=book,
                           user_info=bookshelf.user.user_info)
示例#2
0
def deleted_venue(id):
     
    #get_model().delete_reserve(id)
    #get_model().delete_event(id)
    get_model().delete_venue(id)

    return render_template("adminoptions.html")
示例#3
0
def unlike(id):
    #If the user is not logged, redirect to login
    if bookshelf.user.user_info['log'] == False:
        return redirect(url_for('user.login'))

    get_model().unlike(bookshelf.user.user_info['id'], id)
    return redirect(url_for('.view', id=id))
示例#4
0
def delete(id):
    location = get_model().read(id)
    routes = location["route"].split(",")
    for route in routes:
        delete_route(id, route)
    get_model().delete(id)
    return redirect(url_for('.list'))
示例#5
0
def unlike(id):
    #If the user is not logged, redirect to login
    if session['user']['log'] == False:
        return redirect(url_for('user.login'))

    get_model().unlike(session['user']['id'], id)
    return redirect(url_for('.view', id=id))
示例#6
0
def signup():

    global user_info
    if user_info['id'] is not None:
        return redirect(url_for('crud.list'))

    form = RegisterForm(request.form)

    if request.method == 'POST':
        if form.validate():
            #Checks if the email is already in use
            result = get_model().find_user_email(request.form['email'])
            print(result)
            if result is not None:
                flash('Email is already registered.')
            else:
                # Register successfully
                # We add the user to the database
                data = {}
                data['name'] = request.form['name']
                data['email'] = request.form['email']
                data['balance'] = 0
                data['password'] = cryptography.encrypt_pass(
                    request.form['pass1'])
                result = get_model().create_user(data)
                print(result)
                return redirect(url_for('user.login'))
        else:
            flash('All the form fields are required.')

    return render_template('signup.html', form=form, user_info=user_info)
示例#7
0
def view(id):
    book = get_model().read_comic(id)
    pages, next_page_token = get_model().list_pages(id)
    book['cover'] = pages[0]['url'] if pages else 'http://placekitten.com/g/128/192'

    showPages = request.args.get('showPages')
    showPages = bool(showPages) if showPages is not None else False
    
    publishedBy = get_model().read_user(book['publishedBy'])
    book['publishedBy'] = publishedBy
    bought, showLike, isPublisher = False, False, False
    if session['user']['log'] == True:
        bought = get_model().is_bought(session['user']['id'], id)
        like = get_model().read_like(session['user']['id'], id)
        showLike = True if like is None else False
        isPublisher = True if str(publishedBy['_id']) == str(session['user']['id']) else False
    
    return render_template("view.html",
        book=book,
        pages=pages,
        bought=bought,
        showLike=showLike,
        isPublisher=isPublisher,
        showPages=showPages,
        user_info=session['user'])
示例#8
0
def myeventsandroid(username):
    user = User.query.filter_by(email=username).first()
    events = get_model().see_my_events(user)
    eventids = get_model().see_my_eventids(user)
    allevents = Event.query.all()
    myevents = []
    for event in allevents:
        for eventid in eventids:
            if eventid == event.id:
                myevents.append(event)

    ids, names, descriptions, dates,timeslots,listcurrentusers,listmaxusers,prices,venueids = [], [], [], [],[],[],[],[],[]
    for event in myevents:
        ids.append(event.id)
        names.append(event.eventname)
        descriptions.append(event.description)
        date_of_event = (event.day).strftime("%m/%d/%Y")
        dates.append(date_of_event)
        timeslots.append(event.timeslot)
        listcurrentusers.append(event.currentusers)
        listmaxusers.append(event.maxusers)
        pstring = str(event.price)
        prices.append(pstring)
        venueids.append(event.venue_id)


    events_list = [{"id": i, "eventname": e, "description": d,"date":da,"timeslot":t,"currentusers":cu,"maxusers":mu,"price":pr,"venueid":vid} for i, e,d,da,t,cu,mu,pr,vid in zip(ids, names, descriptions, dates,timeslots,listcurrentusers,listmaxusers,prices,venueids)]
    
    return json.dumps(events_list)
示例#9
0
def view(id):
    book = get_model().read(id)
    avgRating = get_model().readRatings(id)
    ratingReviews = get_model().readReviews(id)
    print(ratingReviews)
    return render_template("view.html",
                           book=book,
                           avgRating=avgRating,
                           ratingReviews=ratingReviews)
示例#10
0
def display_reservations(user_email):
    if request.headers.get("User-Agent") == "Android":
        users = get_model().list_reservations(user_email)
        return jsonify(users)
    
    reservations= get_model().list_reservations(user_email)

     
    return render_template("allevents.html", reservations =reservations)
示例#11
0
文件: crud.py 项目: Tanner1638/swphp
def add2(id):
    order = get_model().read(id)
    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        orders = get_model().create(data)
        
        return redirect(url_for('.view', id=orders['id']))

    return render_template("form2.html", action="CREATE AN", orders={}, order=order)
示例#12
0
def view(id):
    book, comments, book_raw = get_model().read(id)
    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        get_model().add_comment(book_raw, data)

        return redirect(url_for('.view', id=book['id']))

    return render_template("view.html", book=book, comments=comments)
示例#13
0
def delete(id):
    book = get_model().read(id)
    image_url = book.get('imageUrl')
    get_model().delete(id)
    # Async job to delete book image in GCS.
    if image_url:
        image_name = image_url.split('/')[-1]
        q = tasks.get_books_queue()
        q.enqueue(tasks.delete_book_image, image_name)
    return redirect(url_for('.list'))
示例#14
0
def edit(id):
    book = get_model().read(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)
        book = get_model().update(data, id)

        return redirect(url_for('.view', id=book['id']))

    return render_template('form.html', action='Edit', book=book)
示例#15
0
def edit(id):
    book = get_model().read(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)
        book = get_model().update(data, id)

        return redirect(url_for('.view', id=book['id']))

    return render_template('form.html', action='Edit', book=book)
示例#16
0
def joinevent(id):
    event_id = id
    user_id = current_user.get_id()
    if get_model().is_event_full(id):
        flash('Sorry! This event is already full.','danger')
        error = 'Sorry! This event is already full.'
        return redirect(url_for('.eventslist'))
    get_model().join_event(event_id,user_id)
    ####ABOVE THIS WORKS    
    return redirect(url_for('.viewevents', id=id))
示例#17
0
文件: crud.py 项目: Tanner1638/swphp
def editO(id):
    order = get_model().read(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        order = get_model().update(data, id)

        return redirect("/m/orders")

    return render_template("form.html", action="EDIT", orders=order)
示例#18
0
文件: crud.py 项目: Tanner1638/swphp
def edit(id):
    order = get_model().read(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        order = get_model().update(data, id)

        return redirect(url_for('.view', id=order['id']))

    return render_template("form.html", action="EDIT", orders=order)
示例#19
0
def editvenue(id):
    venue = get_model().read(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        venue = get_model().updatevenue(data, id)

        return redirect(url_for('.viewvenue', id=venue['id']))

    return render_template("venueform.html", action="Edit", venue=venue)
示例#20
0
def edituser(id):
    user = get_model().readuser(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        user = get_model().update(data, id)

        return redirect(url_for('.viewuser', id=user['id']))

    return render_template("usersform.html", action="Edit", user=user)
示例#21
0
文件: crud.py 项目: Tanner1638/swphp
def editI(id):
    inventory = get_model().readI(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        inventory = get_model().updateI(data, id)

        return redirect("/m/"+id+"/editI")

    return render_template("inventoryform.html", action="EDIT", inventory=inventory)
示例#22
0
def editevents(id):
    event = get_model().readevent(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        event = get_model().updateevent(data, id)

        return redirect(url_for('.viewevents', id=event['id']))

    return render_template("eventsform.html", action="Edit", event=event)
示例#23
0
def rate(id):
    book = get_model().read(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)
        book = get_model().rate(data, id)
        # This is for viewing each single book in the db
        return redirect(url_for('.view', id=book['id']))

    # This is for adding a newbook to the shelf
    return render_template("rate.html", action="Rate", book=book)
示例#24
0
def view(id):
    location = get_model().read(id)
    token = request.args.get('page_token', None)
    if token:
        token = token.encode('utf-8')
    route_ids = location["route"].split(",")
    routes, next_page_token = get_model().list_routes(route_ids, cursor=token)
    return render_template("view.html",
                           location=location,
                           routes=routes,
                           next_page_token=next_page_token)
示例#25
0
def edit():
    if request.method == 'POST':
        if request.headers.get("User-Agent") == "Android":
            bodyrequest = request.json
            newresdict = {'user_email': bodyrequest['user_email'], 'event_id': bodyrequest['event_id']}
            reservation = get_model().create_reservation(newresdict)
            return jsonify(reservation)
        else: 
            data = request.form.to_dict(flat=True)
            reservation = get_model().create_reservation(data)
    return render_template("join.html", action="Add", reservation={})
示例#26
0
def api_delete_user():
    if not request.get_json(force=True):
        abort(400)
    data = request.get_json(force=True)
    user = get_model().read_user(data["username"])
    location = get_model().delete_user(user["id"])
    if location is not None:
        result = {"result": "true"}
    else:
        result = {"result": "false"}
    return jsonify(result), 201
示例#27
0
def edit(id):
    poo = get_model().read(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        poo = get_model().update(data, id)

        return redirect(url_for('.view', id=poo['id']))

    return render_template("form.html", action="Edit", poo=poo)
示例#28
0
def edit(id):
    question = get_model().read(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        question = get_model().update(data, id)

        return redirect(url_for('.view', id=question['id']))

    return render_template("form.html", action="Edit", question=question)
示例#29
0
def publications(id):

    publications = get_model().find_publications(id)
    publications_with_cover = []
    for book in publications:
        cover = get_model().get_cover(book['id'])
        book = tuple((book, cover))
        publications_with_cover.append(book)

    return render_template('published.html',
                           publications=publications_with_cover,
                           user_info=session['user'])
示例#30
0
def api_list_routes(username):
    location = get_model().read_user(username)
    try:
        route_ids = location["route"].split(",")
    except KeyError:
        route_ids = []
    if len(route_ids) > 0:
        routes = get_model().list_routes_API(route_ids)
    else:
        routes = []

    return jsonify(routes)
示例#31
0
def rate(id):
    book = get_model().read(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)
        print(data)

        book = get_model().rate(data, id)

        return redirect(url_for('.view', id=book['bookid']))

    return render_template("rate.html", action="Review", book=book)
示例#32
0
def edit(id):
    book = get_model().read(id)
    print("edit in crud.py, request method: ", request.method)
    if request.method == 'POST':
        data = request.form.to_dict(flat=True)
        print(data)

        book = get_model().update(data, id)

        return redirect(url_for('.view', id=book['id']))

    return render_template("form.html", action="Edit", book=book)
示例#33
0
文件: crud.py 项目: soliagha/gb-debug
def upload_csv(id):

    report = get_model().read(id)
    csvResponse = ''

    SCHEMA = [
        SchemaField('organizationName_ext', 'STRING', mode='required'),
        SchemaField('organizationName_int', 'STRING', mode='required'),
        SchemaField('organizationID', 'INTEGER', mode='required'),
        SchemaField('amountOver', 'INTEGER', mode='required'),
        SchemaField('amountUnder', 'INTEGER', mode='required'),
        SchemaField('label', 'STRING', mode='required'),
        SchemaField('giftType', 'STRING', mode='required'),
        SchemaField('donorType', 'STRING', mode='required'),
        SchemaField('date', 'STRING', mode='required'),
    ]

    client = bigquery.Client(current_app.config['PROJECT_ID'])
    dataset = client.dataset('Gift')
    # dataset.create()  # API request

    table = dataset.table(id, SCHEMA)

    if request.method == 'POST':
        csvFile = request.files.get('csv')

        if table.exists():
            table.delete()
            table.create()
        else:
            table.create()

        # Save file to cloud via blob
        public_url = storage.upload_file(
           csvFile.read(),
           csvFile.filename,
           csvFile.content_type)

        response = urllib2.urlopen(public_url)
        table.upload_from_file(response, source_format='CSV', skip_leading_rows=1)
        data = report
        data['csvUrl'] = public_url

        get_model().update(data, id)
        report = get_model().read(id)
        csvResponse = 'The CSV was for report ' + report['reportName'] + ' was successfully added to Greasebelt. ' + \
                      'Please click here to request a sync with Fundtracker.'

    return view_csv(id)
    def setUp(self):
        self.app = bookshelf.create_app(
            config,
            testing=True,
            config_overrides={
                'DATA_BACKEND': self.backend
            }
        )

        with self.app.app_context():
            self.model = bookshelf.get_model()

        self.ids_to_delete = []

        # Monkey-patch create so we can track the IDs of every item
        # created and delete them during tearDown.
        self.original_create = self.model.create

        def tracking_create(*args, **kwargs):
            res = self.original_create(*args, **kwargs)
            self.ids_to_delete.append(res['id'])
            return res

        self.model.create = tracking_create

        # Monkey-patch get_books_queue to prevents pubsub events
        # from firing
        self.original_get_books_queue = tasks.get_books_queue
        tasks.get_books_queue = mock.Mock()
示例#35
0
def add():
    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        # If an image was uploaded, update the data to point to the new image.
        # [START image_url]
        image_url = upload_image_file(request.files.get('image'))
        # [END image_url]
        
        current_app.logger.info("Image uploaded. URI: %s" %image_url)
        _url = image_url.split( "/")
        gcfile =  _url[len(_url) - 1]
        gcbucket = _url[len(_url) - 2]
        
        current_app.logger.info("Starting Cloud Vision gcfile : {} : gcbucket : {}".format(gcfile, gcbucket))
        cv_response = cloud_vision.identify_image_attributes_gcs(gcfile, gcbucket)
        #TODO: check and remove json.dumps
        cv_response_pretty = json.dumps(cv_response, indent=4, sort_keys=True)
        # [START image_url2]
        if image_url:
            data['imageUrl'] = image_url
        # [END image_url2]
        if cv_response:
            data['cv_response'] = cv_response_pretty

        book = get_model().create(data)

        return redirect(url_for('.view', id=book['id']))
        

    return render_template("form.html", action="Add", book={})
def edit(id):
    book = get_model().read(id)

    if request.method == "POST":
        data = request.form.to_dict(flat=True)

        image_url = upload_image_file(request.files.get("image"))

        if image_url:
            data["imageUrl"] = image_url

        book = get_model().update(data, id)

        return redirect(url_for(".view", id=book["id"]))

    return render_template("form.html", action="Edit", book=book)
示例#37
0
文件: crud.py 项目: soliagha/gb-debug
def edit(id):
    report = get_model().read(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)
        reportFile = upload_report_file(request.files.get('image'), id)

        if reportFile:
            data['reportUrl'] = reportFile[0]
            data['reportName'] = reportFile[1]

        report = get_model().update(data, id)

        return redirect(url_for('.view', id=report['id']))

    return render_template("form.html", action="Edit", report=report)
示例#38
0
def edit(id):
    book = get_model().read(id)

    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        image_url = upload_image_file(request.files.get('image'))

        if image_url:
            data['imageUrl'] = image_url

        book = get_model().update(data, id)

        return redirect(url_for('.view', id=book['id']))

    return render_template("form.html", action="Edit", book=book)
示例#39
0
def add():
    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        # If an image was uploaded, update the data to point to the new image.
        image_url = upload_image_file(request.files.get('image'))

        if image_url:
            data['imageUrl'] = image_url

        # If the user is logged in, associate their profile with the new book.
        if 'profile' in session:
            data['createdBy'] = session['profile']['displayName']
            data['createdById'] = session['profile']['id']

        book = get_model().create(data)

        # [START enqueue]
        q = tasks.get_books_queue()
        q.enqueue(tasks.process_book, book['id'])
        # [END enqueue]

        return redirect(url_for('.view', id=book['id']))

    return render_template("form.html", action="Add", book={})
示例#40
0
def list():
    token = request.args.get('page_token', None)
    if token:
        token = token.encode('utf-8')

    books, next_page_token = get_model().list(cursor=token)

    return jsonify({'books': books})
示例#41
0
def list():
    token = request.args.get('page_token', None)
    books, next_page_token = get_model().list(cursor=token)

    return render_template(
        "list.html",
        books=books,
        next_page_token=next_page_token)
def list():
    token = request.args.get("page_token", None)
    if token:
        token = token.encode("utf-8")

    books, next_page_token = get_model().list(cursor=token)

    return render_template("list.html", books=books, next_page_token=next_page_token)
示例#43
0
def add():
    if request.method == 'POST':
        data = request.form.to_dict(flat=True)
        book = get_model().create(data)

        return redirect(url_for('.view', id=book['id']))

    return render_template('form.html', action='Add', book={})
示例#44
0
def list():
    token = request.args.get('page_token', None)
    if token:
        token = token.encode('utf-8')

    books, next_page_token = get_model().list(cursor=token)

    return render_template('list.html', books=books,
                           next_page_token=next_page_token)
示例#45
0
def list():
    current_app.logger.info("enter crud.list")
    token = request.args.get('page_token', None)
    books, next_page_token = get_model().list(cursor=token)

    return render_template(
        "list.html",
        books=books,
        next_page_token=next_page_token)
示例#46
0
def add():
    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        poo = get_model().create(data)

        return redirect(url_for('.view', id=poo['id']))

    return render_template("form.html", action="Add", poo={})
示例#47
0
def view(id):
    book = get_model().read(id)
    
    if book['cv_response']:
        cv_response = json.loads(book['cv_response'])
        attrib_info = cloud_vision.get_attributes_info(cv_response, "BIRD", True)
        book['birdInfo'] = attrib_info

    _book = dict(book)
    
    return render_template("view.html", book=_book)
示例#48
0
文件: crud.py 项目: soliagha/gb-debug
def add():
    if request.method == 'POST':

        data = request.form.to_dict(flat=True)
        report = get_model().create(data)

        if request.files.get('image'):
            try:
                reportFile = upload_report_file(request.files.get('image'), report['id'])
                data['reportUrl'] = reportFile[0]
                data['reportName'] = reportFile[1]

            except:
                print ('Report file upload failed!')

            get_model().update(data, report['id'])

        return redirect(url_for('.view', id=report['id']))

    return render_template("form.html", action="Add", report={})
示例#49
0
def list_mine():
    token = request.args.get('page_token', None)

    books, next_page_token = get_model().list_by_user(
        user_id=session['profile']['id'],
        cursor=token)

    return render_template(
        "list.html",
        books=books,
        next_page_token=next_page_token)
示例#50
0
文件: crud.py 项目: soliagha/gb-debug
def view_csv(id):

    report = get_model().read(id)

    if not report['csvUrl']:
        upload_csv(id)

    else:
        credentials = GoogleCredentials.get_application_default()
        service = discovery.build('bigquery', 'v2', credentials=credentials)
        projectId = current_app.config['PROJECT_ID']
        datasetId = 'Gift'
        tableId = id

        bq_request = service.tabledata().list(projectId=projectId, datasetId=datasetId, tableId=tableId)
        data = bq_request.execute()

        rowCollection = []
        headerRow = []

        # __file__ refers to the file settings.py
        APP_ROOT = os.path.dirname(os.path.abspath(__file__))   # refers to application_top
        APP_CSV = os.path.join(APP_ROOT, 'csv/placeholder.csv')

        # csvFile = file('/csv/test.csv')
        csvFile = open(APP_CSV, 'w+')
        a = csv.writer(csvFile)

        for row in data['rows']:
            rowVal = []
            for cell in row['f']:
                rowVal.append(cell['v'])
            rowCollection.append(rowVal)

        headerRow.append(['organizationName_ext', 'organizationName_int', 'organizationID', 'amountOver', 'amountUnder', 'label', 'giftType', 'donorType', 'date'])
        a.writerows(headerRow)
        a.writerows(rowCollection)

        # Save file to cloud via blob
        public_url = storage.upload_file(
            csvFile.read(),
            report['reportName'] + '.csv',
            'text/csv')

        csvFile.close()
        csvRender = rowCollection

        csvResponse = ''

    return render_template("csv.html", report=report, csvResponse=csvResponse, csvRender=csvRender, public_url=public_url)
示例#51
0
文件: crud.py 项目: soliagha/gb-debug
def delete(id):

    report = get_model().read(id)

    try:  # Delete CSV data
        client = bigquery.Client(current_app.config['PROJECT_ID'])
        dataset = client.dataset('Gift')
        dataset.table(id).delete()
    except:
        print ('Deleting CSV failed for report: ' + id)
        print ('It is possible there is no report file associated to this report record.')

    try:  # Delete report blob
        storage.delete_file(report['reportUrl'])
    except :
        print ('Deleting report blob failed for report ID ' + id)

    try:  # Delete Greasebelt report
        get_model().delete(id)
    except:
        print ('Deleting Greasebelt report failed for report ID ' + id)

    return redirect(url_for('.list'))
示例#52
0
def process_book(book_id):
    """
    Handles an individual Bookshelf message by looking it up in the
    model, querying the Google Books API, and updating the book in the model
    with the info found in the Books API.
    """

    model = get_model()

    book = model.read(book_id)

    if not book:
        logging.warn("Could not find book with id {}".format(book_id))
        return

    if 'title' not in book:
        logging.warn("Can't process book id {} without a title."
                     .format(book_id))
        return

    logging.info("Looking up book with title {}".format(book[
                                                        'title']))

    new_book_data = query_books_api(book['title'])

    if not new_book_data:
        book['something'] = "book not found in api"
        model.update(book, book_id)
        return

    book['title'] = new_book_data.get('title')
    book['author'] = ', '.join(new_book_data.get('authors', []))
    book['publishedDate'] = new_book_data.get('publishedDate')
    book['description'] = new_book_data.get('description') + "________added_this"
    book['something'] = "book api found this one"


    # If the new book data has thumbnail images and there isn't currently a
    # thumbnail for the book, then copy the image to cloud storage and update
    # the book data.
    if not book.get('imageUrl') and 'imageLinks' in new_book_data:
        new_img_src = new_book_data['imageLinks']['smallThumbnail']
        book['imageUrl'] = download_and_upload_image(
            new_img_src,
            "{}.jpg".format(book['title']))

    model.update(book, book_id)
示例#53
0
文件: crud.py 项目: soliagha/gb-debug
def list():
    token = request.args.get('page_token', None)
    if token:
        token = token.encode('utf-8')

    search = []

    if request.method == 'POST':
        search = request.form.to_dict(flat=True)

    reports, next_page_token = get_model().list(
        cursor=token, search=search)

    return render_template(
        "list.html",
        reports=reports,
        next_page_token=next_page_token,
        search=search)
def add():
    if request.method == 'POST':
        data = request.form.to_dict(flat=True)

        # If an image was uploaded, update the data to point to the new image.
        # [START image_url]
        image_url = upload_image_file(request.files.get('image'))
        # [END image_url]

        # [START image_url2]
        if image_url:
            data['imageUrl'] = image_url
        # [END image_url2]

        book = get_model().create(data)

        return redirect(url_for('.view', id=book['id']))

    return render_template("form.html", action="Add", book={})
示例#55
0
def process_book(book_id):
    """
    Handles an individual Bookshelf message by looking it up in the
    model, querying the Google Books API, and updating the book in the model
    with the info found in the Books API.
    """

    model = get_model()

    book = model.read(book_id)

    if not book:
        logging.warn("Could not find book with id {}".format(book_id))
        return

    if "title" not in book:
        logging.warn("Can't process book id {} without a title.".format(book_id))
        return

    logging.info("Looking up book with title {}".format(book["title"]))

    new_book_data = query_books_api(book["title"])

    if not new_book_data:
        return

    book["title"] = new_book_data.get("title")
    book["author"] = ", ".join(new_book_data.get("authors", []))
    book["publishedDate"] = new_book_data.get("publishedDate")
    book["description"] = new_book_data.get("description")

    # If the new book data has thumbnail images and there isn't currently a
    # thumbnail for the book, then copy the image to cloud storage and update
    # the book data.
    if not book.get("imageUrl") and "imageLinks" in new_book_data:
        new_img_src = new_book_data["imageLinks"]["smallThumbnail"]
        book["imageUrl"] = download_and_upload_image(new_img_src, "{}.jpg".format(book["title"]))

    model.update(book, book_id)
def model(monkeypatch, app):
    """This fixture provides a modified version of the app's model that tracks
    all created items and deletes them at the end of the test.

    Any tests that directly or indirectly interact with the database should use
    this to ensure that resources are properly cleaned up.

    Monkeypatch is provided by pytest and used to patch the model's create
    method.

    The app fixture is needed to provide the configuration and context needed
    to get the proper model object.
    """
    model = bookshelf.get_model()

    # Ensure no books exist before running. This typically helps if tests
    # somehow left the database in a bad state.
    delete_all_books(model)

    yield model

    # Delete all books that we created during tests.
    delete_all_books(model)
示例#57
0
文件: crud.py 项目: soliagha/gb-debug
def view(id):
    report = get_model().read(id)
    return render_template("view.html", report=report)
def view(id):
    book = get_model().read(id)
    return render_template("view.html", book=book)
def delete(id):
    get_model().delete(id)
    return redirect(url_for('.list'))
示例#60
0
def view(id):
    book = get_model().read(id)
    if not book:
        abort(404)
    return render_template('view.html', book=book)