Ejemplo n.º 1
0
    def setUp(self):

        '''
        Set up method that will run before every
        
        '''
        self.new_quote = Quote(4,'shaz', 'amazing deeds are just but gifts')
Ejemplo n.º 2
0
 def setUp(self):
     '''
     Set up method that will run before every
     
     '''
     self.new_quote = Quote(1, 'erastus',
                            'its amaizing i have come this far')
Ejemplo n.º 3
0
 def setUp(self):
     '''
     Set up method that will run before every Test
     '''
     self.new_quote = Quote(
         1234, 'Fred Brooks',
         'No such faith comforts the software engineer.')
Ejemplo n.º 4
0
    def handle(self, *args, **options):
        # if Quote.objects.count() > 0:
        #     sys.exit('Not an empty DB, cowardly exiting')

        username = options['username']
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            error = (f'User {username} does not exist in DB, create it '
                     'via manage.py or register on the quotes site')
            sys.exit(error)

        try:
            max_quotes = int(options['limit'])
        except ValueError:
            sys.exit('Please specify an numeric value for limit')

        resp = requests.get(INSPIRATIONAL_QUOTES)
        lines = resp.text.strip().splitlines()

        headers = 'quote author genre'.split()
        reader = csv.DictReader(lines, fieldnames=headers, delimiter=';')

        quotes_lst = []
        # ignore header / TODO shuffle quotes?
        for row in list(reader)[1:max_quotes + 1]:
            quote = Quote(quote_txt=row['quote'],
                          author=row['author'],
                          user=user)
            quotes_lst.append(quote)

        Quote.objects.bulk_create(quotes_lst)

        print(f'Done: {max_quotes} quotes created')
Ejemplo n.º 5
0
def seeds(create_database):
    user = User(
        name="Marcus Pereira",
        email="*****@*****.**",
        password=generate_password_hash("12345"),
        is_admin=True,
    )

    db.session.add(user)
    db.session.commit()

    course = Course(
        name="Curso de test",
        slug="curso-de-test",
        description="alguma coisa...",
        duration=300,
        video_url="http://fake:4000/video",
        source_code_url="http://fake:4000/source",
        release_date=datetime.utcnow(),
        author_id=user.id,
    )
    tag = Tag(name="python")
    tag2 = Tag(name="javascript")
    tag3 = Tag(name="flask")

    course.tags.append(tag)
    course.tags.append(tag2)
    course.tags.append(tag3)

    db.session.add(course)
    db.session.commit()

    db.session.add(
        Quote(title="1. introduction", quote_time=20, course_id=course.id))
    db.session.commit()
Ejemplo n.º 6
0
    def handle(self, *args: Any, **options: Any) -> None:
        """Handles records creation."""
        if Quote.objects.count() > 0:
            sys.exit("Not an empty DB, cowardly exiting")

        username: str = options["username"]
        try:
            user: User = User.objects.get(username=username)
        except User.DoesNotExist:  # pylint: disable=no-member
            error: str = (
                f"User {username} does not exist in DB, create it "
                "via manage.py or register on the quotes site"
            )
            sys.exit(error)

        try:
            max_quotes: int = int(options["limit"])
        except ValueError:
            sys.exit("Please specify an numeric value for limit")

        headers: List[str] = "quote author genre".split()
        reader = DictReader(
            requests.get(self.QUOTES_URL).text.strip().splitlines(),
            fieldnames=headers,
            delimiter=";",
        )

        quotes: List[Quote] = []
        for row in list(reader)[1 : max_quotes + 1]:
            quotes.append(
                Quote(quote=row["quote"], author=row["author"], user=user)
            )

        Quote.objects.bulk_create(quotes)
        print(f"Done: {max_quotes} quotes created")
Ejemplo n.º 7
0
def updates():
    with RESTClient(apiKey) as client:
        return7days = (datetime.now() - timedelta(days=1)).date()
        # return7days = (datetime.now() - timedelta(days=20)).date()
        response = client.stocks_equities_grouped_daily('us',
                                                        'stocks',
                                                        return7days,
                                                        unadjusted=True)
    api_results = response.results
    quotes = list()
    for result in api_results:
        quotes.append(
            Quote(
                id=uuid.uuid4(),
                ticker=result.get('T'),
                volume=result.get('v'),
                volume_weighted_avg_price=result.get('vw'),
                open=result.get('o'),
                adj_close=result.get('c'),
                close=result.get('c'),
                high=result.get('h'),
                low=result.get('l'),
                date_time=ts_to_date(result.get('t')),
            ))
    save_quotes(quotes)
    return render_template("updates.html", source=quotes)
Ejemplo n.º 8
0
async def on_message(message: discord.message):
    if message.author == client.user or not message.content.startswith('!q'):
        return
    body = message.content[2:].strip()
    server = message.channel.guild
    if message.mentions:
        for mention in message.mentions:
            db.session.add(
                Quote(user_id=mention.id,
                      reporter_id=message.author.id,
                      server_id=server.id,
                      body=body))
        db.session.commit()
        return
    # if there are no mentions, get a quote, but only from the server
    quote = random.choice(Quote.query.filter_by(server_id=server.id).all())
    quote_with_nicknames = replace_mentions_with_nickname_for_server(
        server, quote.body)
    should_add_shit_pants_quote = random.randint(0, 100) <= shit_pants_percent
    message_to_send = "{} {}".format(
        get_easter_egg_quote() if should_add_shit_pants_quote else "",
        quote_with_nicknames).strip()
    formatted_message = '''
```
''' + message_to_send + '''
```
'''
    await message.channel.send(formatted_message)
Ejemplo n.º 9
0
 def setUp(self):
     '''
     Set up method that will run before every Test
     '''
     self.new_quote = Quote(
         "James O. Coplien", 23,
         "You should name a variable using the same care with which you name a first-born child.",
         "http://quotes.stormconsultancy.co.uk/quotes/23")
Ejemplo n.º 10
0
 def setUp(self):
     '''
     set up method that will run before every test
     '''
     self.new_quote = Quote(
         22, "Ovidiu Platon",
         "I don’t care if it works on your machine! We are not shipping your machine!"
     )
Ejemplo n.º 11
0
 def setUp(self):
     '''
     function executes before every test
     '''
     self.new_quote = Quote(
         1, 'Terry Pratchett',
         'Studies have shown that an ant can carry one hundred times its own weight, but there is no known limit to the lifting power of the average tiny eighty-year-old Spanish peasant grandmother'
     )
Ejemplo n.º 12
0
 def setUp(self):
     """
     Set up method that will run before every Test
     """
     self.new_quote = Quote(
         1234,
         "Bill Gate",
         "Starting is the beginning",
     )
Ejemplo n.º 13
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)
Ejemplo n.º 14
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()
Ejemplo n.º 15
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
Ejemplo n.º 16
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
Ejemplo n.º 17
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)
Ejemplo n.º 18
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)
Ejemplo n.º 19
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'))
Ejemplo n.º 20
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)
Ejemplo n.º 21
0
 def clean(self):
     id = self.cleaned_data.get('id')
     name = self.cleaned_data.get('name')
     email = self.cleaned_data.get('email')
     if not name:
         raise forms.ValidationError('name is required')
     if not email:
         raise forms.ValidationError('email is required')
     if id:
         quote = Quote.objects.get(id=id)
         quote.name = name
         quote.email = email
     else:
         quote = Quote(name=name, email=email)
     quote.save()
Ejemplo n.º 22
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
Ejemplo n.º 23
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
Ejemplo n.º 24
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)
Ejemplo n.º 25
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
Ejemplo n.º 26
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
Ejemplo n.º 27
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"})
Ejemplo n.º 28
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
Ejemplo n.º 29
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)
Ejemplo n.º 30
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()