Exemplo n.º 1
0
def quote_add():
    template = env.get_template('quote_add.html')
    all_quotes = Quote.select()
    if request.method == 'POST':
        quote = Quote.create(text=post_get('text'),
                             author=post_get('author'))
        app.flash('Quote added', 'success')
    return template.render({'quotes': all_quotes})
Exemplo n.º 2
0
def quote_delete(quote_id):
    try:
        quote = Quote.get(Quote.quote_id == quote_id)
        quote.delete_instance()
        app.flash('Quote removed', 'success')
        redirect('/quote/add')
    except DoesNotExist:
        abort(404)
Exemplo n.º 3
0
 def setUp(self):
     """
     Set up method that will run before every Test
     """
     self.new_quote = Quote(
         1234,
         "Bill Gate",
         "Starting is the beginning",
     )
Exemplo n.º 4
0
def index():
    form = QuoteForm()
    quotes = Quote.query.order_by(Quote.timestamp.desc()).all()
    if form.validate_on_submit():
        quote = Quote(title=form.title.data, body=form.body.data, by=form.by.data)
        db.session.add(quote)
        db.session.commit()
        flash('Thank you for sharing!')
        return redirect(url_for('index'))
    return render_template('index.html', form=form, quotes=quotes)
Exemplo n.º 5
0
class QuoteTest(unittest.TestCase):  
   
    def setUp(self):
        self.new_quote = Quote(1,'pass','Technology','http//:www.reginah.com')
        
    def test_check_instance_variables(self):
        self.assertEquals(self.new_quote.id,1)
        self.assertEquals(self.new_quote.author,'pass')
        self.assertEquals(self.new_quote.quote,"Technology")
        self.assertEquals(self.new_quote.link,'http//:www.reginah.com')
        
    def test_save_quote(self):
        self.new_quote.save_quote()
        self.assertTrue(len(Quote.quote_list),0)
        
    def test_get_blog_by_id(self):

        self.new_quote.save_quote()
        got_quote = Quote.get_quote(1)
Exemplo n.º 6
0
class QuoteTest(unittest.TestCase):  
   
    def setUp(self):
        self.new_quote = Quote(1,'blue','inventory','http//:www.roba.com')
        
    def test_check_instance_variables(self):
        self.assertEquals(self.new_quote.id,1)
        self.assertEquals(self.new_quote.author,'blue')
        self.assertEquals(self.new_quote.quote,"inventory")
        self.assertEquals(self.new_quote.permalink,'http//:www.roba.com')
        
    def test_save_quote(self):
        self.new_quote.save_quote()
        self.assertTrue(len(Quote.quote_list),0)
        
    def test_get_blog_by_id(self):

        self.new_quote.save_quote()
        got_quote = Quote.get_quote(1)
Exemplo n.º 7
0
def get_quote():
    with urllib.request.urlopen(quote_url) as url:
        quote_response = json.loads(url.read())

        quote_result = None

        if quote_response:
            author = quote_response.get('author')
            quote = quote_response.get('quote')
            quote_result = Quote(author, quote)

        return quote_result
Exemplo n.º 8
0
def process_results(quote_list):
    '''
    Process quote
    '''
    final_quote = []

    quote = quote_list
    author = quote_list

    quote_component = Quote(quote, author)
    final_quote.append(quote_component.quote)
    return final_quote
Exemplo n.º 9
0
def get_a_quote():
    """Return rendered template for '/get-a-quote' if GET and handle QuoteForm POST."""
    form = QuoteForm()
    if form.validate_on_submit():
        dt_now = datetime.utcnow()
        # Security consideration: rate limiting implementation
        if "last_quote" in session:
            # Calculate the time difference between now and the last quote
            last_quote_timedelta = dt_now - session["last_quote"]
            if last_quote_timedelta < timedelta(seconds=60):
                # Rate limit the quote request: flash rate limit warning and return the form unsubmitted
                flash(
                    "Quote request not added to database: rate-limited for attempting "
                    f"to request a quote within 1 minute of the last request at {session['last_quote']}."
                )
                return render_template("get_quote.html",
                                       title="Get a Quote!",
                                       form=form)

        # Filter quotes by email address specified in the form
        quotes_for_email = Quote.query.filter_by(email=form.email.data)
        # Get the count of previous quotes for email
        quotes_count = quotes_for_email.count()
        if quotes_count >= 5:
            # Log a warning that this email has made quotes_count previous quote requests
            app.logger.warning(
                f"{quotes_count} previous quotes for {form.email.data} at {last_quote._datetime}"
            )

        quote = Quote(email=form.email.data,
                      forename=form.forename.data,
                      surname=form.surname.data,
                      telephone=form.telephone.data,
                      account_number=form.account_number.data,
                      sort_code=form.sort_code.data,
                      address=form.address.data,
                      town=form.town.data,
                      postcode=form.postcode.data,
                      _datetime=dt_now)
        db.session.add(quote)
        db.session.commit()
        flash("Quote request added to database!")
        # Set information in session and goto thanks
        session["last_quote"] = dt_now
        session["email"] = form.email.data
        session["forename"] = form.forename.data
        return redirect(url_for("thanks"))
    elif form.is_submitted():
        app.logger.info(
            f"{type(form).__name__} validation failure by "
            f"{request.remote_addr} with {request.user_agent}: {form.errors}")

    return render_template("get_quote.html", title="Get a Quote!", form=form)
Exemplo n.º 10
0
def index():
    try:
        request = requests.get(
            'http://quotes.stormconsultancy.co.uk/random.json')
        res_json = request.json()
        author = res_json.get('author')
        quote = res_json.get('quote')
        link = res_json.get('permalink')
        quote = Quote(author, quote, link)
    except Exception:
        quote = None
    blogs = Blog.query.all()
    return render_template('index.html', quote=quote, blogs=blogs)
Exemplo n.º 11
0
def submit(request):
    if request.method == 'POST':
        quote = Quote(
            text=request.POST['text'],
            submitter=request.user,
            )
        quote.save()
        tag_string = request.POST['tags']
        if len(tag_string) > 0:
            tag_texts = [Tag.make_valid_tag(text.strip()) for text in
                         tag_string.split(',')]
            for text in tag_texts:
                if len(text) > 0:
                    tag = Tag.objects.filter(text=text).first()
                    if tag is None:
                        tag = Tag(text=text)
                        tag.save()
                    quote.tags.add(tag)
        return redirect(reverse('app:detail', args=(quote.id,)))
    form = QuoteForm()
    context = {'form': form}
    return render(request, 'app/submit.html', context)
Exemplo n.º 12
0
def loadquotes():
    quotes = [
        Quote(line1="Oh what'll you do now, my blue eyed son?",
              line2="What'll you do now, my darling young one?",
              cite="Bob Dylan",
              context="hardrain",
              order=0),
        Quote(line1="I'm goin' back out 'fore the rain starts fallin'",
              line2="Walk to the depths of the deepest black forest",
              cite="Bob Dylan",
              context="hardrain",
              order=1),
        Quote(line1="Where people are many and their hands are all empty",
              line2="Where pellets of poison are flooding the waters",
              cite="Bob Dylan",
              context="hardrain",
              order=2),
        Quote(line1="Where the home in the valley meets the damp dirty prison",
              line2="Where the executioner's face is always well hidden",
              cite="Bob Dylan",
              context="hardrain",
              order=3),
        Quote(line1="Where hunger is ugly, where souls are forgotten",
              line2="Where black is the color, and none is the number",
              cite="Bob Dylan",
              context="hardrain",
              order=4),
        Quote(
            line1="And I'll tell it and think it and speak it and breathe it",
            line2="And reflect it from the mountains so all souls can see it",
            cite="Bob Dylan",
            context="hardrain",
            order=5),
        Quote(line1="Then I'll stand in the ocean until I start sinking",
              line2="But I'll know my song well before I start singing",
              cite="Bob Dylan",
              context="hardrain",
              order=6),
        Quote(line1="And it's a hard, it's a hard, and it's a hard",
              line2="And it's a hard rain's a gonna fall",
              cite="Bob Dylan",
              context="hardrain",
              order=7)
    ]
    for quote in quotes:
        db.session.add(quote)
        db.session.commit()
    return redirect(url_for('index'))
Exemplo n.º 13
0
def import_quote():
    click.echo("Importing Quote...", nl=False)
    with open("./data/quotes.json") as data_file:
        quotes = json.load(data_file)

    for i, quote in enumerate(quotes, start=1):
        q = Quote(
            id=i,
            text=quote["text"],
            date=parser.parse(quote["date"]).date(),
            medium=quote["medium"],
        )
        if "email_id" in quote:
            q.email_id = quote["email_id"]
        if "post_id" in quote:
            q.post_id = quote["post_id"]
        categories = []
        for cat in quote["category"].split(", "):
            categories += [get(QuoteCategory, slug=cat)]
        q.categories = categories
        db.session.add(q)
    db.session.commit()
    click.echo(DONE)
Exemplo n.º 14
0
 def setUp(self):
     self.user_Emmanuel = User(username='******',
                               password='******',
                               email='*****@*****.**')
     self.new_quote = Quote(id=1,
                            quote_title='Test',
                            quote_content='This is a test quote',
                            category="interview",
                            user=self.user_Emmanuel,
                            likes=0,
                            dislikes=0)
     self.new_comment = Comment(id=1,
                                comment='Test comment',
                                user=self.user_Emmanuel,
                                quote=self.new_quote)
Exemplo n.º 15
0
def approve_quote(modeladmin, request, queryset):
    for submitted_quote in queryset:
        new_quote = Quote()
        new_quote.quote = submitted_quote.quote
        new_quote.attribution = submitted_quote.attribution
        new_quote.save()
        #send a notification email
        if submitted_quote.submitter_email != '':
            send_approve_email(submitted_quote.submitter_email, new_quote.pk)
        submitted_quote.delete()
Exemplo n.º 16
0
def update():
    start = time.time()
    try:
        data = helpers.ws_get_positions()
    except:
        app.logger.debug("Unexpected error: {}".format(sys.exc_info()))
        resp = make_response(Markup(), 500)
        return resp
    portfolios = {}
    for key, entry in data.items():
        # POSITION HANDLING ---------------------------------------
        # if entry["account_id"] not in portfolios.keys():
        #     port = Portfolio(entry["account_id"])
        #     portfolios.update({entry["account_id"]: port})
        # else:
        #     port = portfolios[entry["account_id"]]
        # port.positions.append(Stock(entry))
        try:
            # QUOTE HANDLING -----------------------------
            for line in entry['sparkline']:
                if not line['close']:
                    continue
                timestamp = parser.parse(line['date'] + " " + line['time'])
                timestamp = timestamp.replace(
                    tzinfo=pytz.timezone("US/Eastern"))
                q = Quote(symbol=key, value=line['close'], timestamp=timestamp)
                db.session.add(q)
                url = "http://elk.nod.lan:8086/write?db=stocks&precision=s"
                data = f"quotes,symbol={key} value={line['close']} {int(timestamp.timestamp())}"
                try:
                    write = requests.post(url, data=data)
                except:
                    pass
                try:
                    db.session.commit()
                except exc.IntegrityError:
                    db.session.rollback()
            # /QUOTE HANDLING ----------------------------
        except KeyError:
            app.logger.debug(f"There was an error updating {key}...\n",
                             exc_info=True)
            # return make_response(jsonify(entry), 500)
            continue
        # /POSITION HANDLING ---------------------------------------
    end = time.time()
    resp = make_response('', 200)
    resp.headers['X-Time-Elapsed'] = end - start
    return resp
Exemplo n.º 17
0
def my_quotes():
    get_quote_url = 'http://quotes.stormconsultancy.co.uk/random.json'

    with urllib.request.urlopen(get_quote_url) as url:
        quote_details_data = url.read()
        quote_details_response = json.loads(quote_details_data)

        quote_object = None
        
        if quote_details_response:
            id = quote_details_response.get('id')
            author = quote_details_response.get('author')
            quote = quote_details_response.get('quote')
            permalink = quote_details_response.get('permalink')
            
            quote_object = Quote(id, author, quote, permalink)
    return quote_object
Exemplo n.º 18
0
def new_quote():
    form = QuoteForm()
    if form.validate_on_submit():
        quote = Quote(
            author=current_user,
            gallons_requested=form.gallons_requested.data,
            date_requested=form.date_requested.data,
            delivery_address=form.delivery_address.data,
            suggested_price=form.suggested_price.data,
            total_amount_due=form.total_amount_due.data,
        )
        db.session.add(quote)
        db.session.commit()
        flash('Your quote has been requested', 'success')
        return redirect(url_for('main.home'))
    elif request.method == 'GET':
        form.delivery_address.data = current_user.user_profile.address_one + ', ' + current_user.user_profile.address_two  # current_user.user_profile.address_one
    return render_template('create_quote.html', title='New Quote', form=form)
Exemplo n.º 19
0
def get_quote():
    '''
    Function to get random quote
    '''

    with urllib.request.urlopen(quote_url) as url:
        quote_data = url.read()
        quote_response = json.loads(quote_data)

        quote_result = None

        if quote_response:
            author = quote_response.get('author')
            quote = quote_response.get('quote')
            permalink = quote_response.get('permalink')

            quote_result = Quote(author, quote, permalink)

        return quote_result
Exemplo n.º 20
0
def save_quote():
    """
    Endpoint to save quote; called by js-function.

    Args:
        quote_id (str): id of quote
        image_id (str): id of image
        quote (str): quote (English language) to be processed
        author (str): author name

    Returns succes or failure

    For now, a manual check on constraints (check uniqueness), because
    SQLlite does not support these constrains.

    Authentication needed
    """
    if not is_valid_request(request.form,
                            ["quote_id", "image_id", "quote", "author"]):
        return jsonify(
            {"error": "Could not save quote, due to technical reasons"})
    quote_id = request.form["quote_id"]
    image_id = request.form["image_id"]
    quote = request.form["quote"]
    author = request.form["author"]

    check_uniqueness = (Quote.query.filter_by(user=current_user).filter_by(
        quote_id=quote_id).filter_by(image_id=image_id).count())

    if check_uniqueness == 0:
        quote = Quote(
            quote_id=quote_id,
            image_id=image_id,
            quote=quote,
            author=author,
            user=current_user,
        )
        db.session.add(quote)
        db.session.commit()
        return jsonify({"succes": "Quote saved"})
    else:
        return jsonify({"error": "Quote already saved"})
Exemplo n.º 21
0
def add_quote(request):
    if request.method == 'POST':
        print request.POST
        post_quote = ''
        post_comment = ''
        post_author = ''

        quote_form = QuoteForm(request.POST.copy(), prefix='quote')
        if quote_form.is_valid():
            cd = quote_form.cleaned_data
            post_quote = cd['quote']
            post_comment = cd['comment']
            post_author = cd['author']

            quote = Quote()

            if post_comment:
                print 'post_comment',post_comment
                comment = Comment()
                comment.text = post_comment
                comment.save()
                quote.comment = comment

            author, created = Author.objects.get_or_create(name__iexact=post_author)
            if post_author:
                author.name = post_author
            else:
                author.name = 'Anonymous'
            author.save()

            quote.author = author
            quote.quote = post_quote
            quote.save()
        else:
            print "Quote_form is not valid!"
        
        data = {
            'quote_text': post_quote,
            'quote_comment': post_comment,
            'quote_author': post_author,
        }

        return HttpResponse(simplejson.dumps(data))
    raise Http404
Exemplo n.º 22
0
def post_index():
    all_posts = Post.get_posts(index_only=True)\
        .order_by(Post.date_posted.desc())\
        .limit(config.POSTS_PER_PAGE)

    for item in all_posts:
        item.post_text = shorten_text(item.post_text)

    random_banner = Banner.select()\
        .where(Banner.disabled == False)\
        .order_by(fn.Rand())\
        .first()
    quote = Quote.select().order_by(fn.Rand()).first()
    messages = StreamMessage.select()

    template = env.get_template('post/index.html')
    return template.render(posts=all_posts, banner=random_banner,
                           stream_messages=messages,
                           quote=quote,
                           link_what='pstlink')
Exemplo n.º 23
0
def post_index():
    all_posts = Post.get_posts(index_only=True)\
        .order_by(Post.date_posted.desc())\
        .limit(config.POSTS_PER_PAGE)

    for item in all_posts:
        item.post_text = shorten_text(item.post_text)

    random_banner = Banner.select()\
        .where(Banner.disabled == False)\
        .order_by(fn.Rand())\
        .first()
    quote = Quote.select().order_by(fn.Rand()).first()
    messages = StreamMessage.select()

    template = env.get_template('post/index.html')
    return template.render(posts=all_posts,
                           banner=random_banner,
                           stream_messages=messages,
                           quote=quote,
                           link_what='pstlink')
Exemplo n.º 24
0
    def setUp(self):
        '''
    runs at the beginning of eah test to set up th attributes
    '''
        self.new_user = User(email='*****@*****.**',
                             username='******',
                             password='******',
                             prof_pic='path/to/image',
                             bio="I love flowers",
                             role_id=1)

        self.new_blog = Blog(title="Monday",
                             category="Tuesday",
                             blog_body="Wednesday")

        self.new_comment = Comment(comment_body="Friday", blog_id=3, user_id=1)

        self.new_quote = Quote(id=2, author="James", quote="Play Nice")

        db.session.add(self.new_user)
        db.session.add(self.new_blog)
        db.session.add(self.new_comment)
        db.session.commit()
Exemplo n.º 25
0
def get_list_quote(quote_df, db):
    li_no_company = []
    for tup in quote_df.itertuples():
        compagnie = Company.query.filter_by(company_name=tup.nom_entreprise)
        if compagnie.count() == 1:
            quote_params = {
                'ref_quote': tup.ref_devis,
                'quote_status': tup.statuts_devis,
                'created_at': tup.date_devis,
                'company': compagnie.first()
            }

            quote = Quote(**quote_params)
            db.session.add(quote)
            db.session.commit()
        else:
            li_no_company.append({
                'nb_comp': compagnie.count(),
                'nom_entreprise': tup.nom_entreprise,
                'ref_quotr': tup.ref_devis,
                #'ref_invoice': tup.ref_facture
            })
    return li_no_company
Exemplo n.º 26
0
def save_quote():
    logging.warning("Json is here")
    quote = request.get_json(force=True)
    company_id = quote["company_id"]
    client_id = int(quote["client_id"])
    items = quote["items"]
    object_name = quote["object_name"]
    total = float(quote["total"])
    vat = float(quote["vat"])
    totalwithwat = float(quote["totalwithvat"])
    newquote = Quote(client_id=client_id,
                     company_id=company_id,
                     user_id=current_user.id,
                     object_name=object_name,
                     total=total,
                     vat=vat,
                     totalwithvat=totalwithwat)
    db.session.add(newquote)
    db.session.commit()
    quote_id = newquote.id
    for item in items:
        if item["is_category"]:
            newitem = Item(quote_id=quote_id,
                           name=item["name"],
                           description=item["description"],
                           is_category=True)
        else:
            newitem = Item(quote_id=quote_id,
                           name=item["name"],
                           description=item["description"],
                           unit=item["unit"],
                           price_per_unit=float(item["price"]),
                           units=float(item["units"]))
        db.session.add(newitem)
        db.session.commit()
    return jsonify(error=200)
Exemplo n.º 27
0
 def setUp(self):
     '''
     Set up method that will run before every
     
     '''
     self.new_quote = Quote(4, 'jane', 'amazing deeds are just but gifts')
Exemplo n.º 28
0
 def setUp(self):
     
     self.new_quote = Quote('hamisi','I have no quote')
Exemplo n.º 29
0
 def setUp(self):
     """
     Set up method that will run before every Test
     """
     self.random_quote = Quote("Tony Stark", "Hello World")
Exemplo n.º 30
0
 def setUp(self):
     """
     Set up method that will run before every Test
     """
     self.quote = Quote("Vector", "Passion is the cost for success")
Exemplo n.º 31
0
    def test_get_blog_by_id(self):

        self.new_quote.save_quote()
        got_quote = Quote.get_quote(1)
Exemplo n.º 32
0
 def setUp(self):
     """
     Set up method that will run before every Test
     """
     self.random_quote = Quote('Nimo', 'You are loved')
Exemplo n.º 33
0
 def setUp(self):
     '''
     Set up method that will run before every Test
     '''
     self.new_quote = Quote(12, 'Title', 'Python Must Be Crazy', '#')
Exemplo n.º 34
0
 def setUp(self):
     self.new_quote = Quote(1,'pass','Technology','http//:www.reginah.com')