def post(self): data = request.get_json() quote_text = data['quote'] quote = Quote(quote_text) try: quote.save_to_database() except Exception as e: print(e) return {'message': 'An error occurred inserting the quote'}, 500 return quote.json(), 201
def scrape_stands4(): # make api call scrape_url = 'http://www.stands4.com/services/v2/quotes.php?' params = { 'uid': config.stands4_id, 'tokenid': config.stands4_token, 'searchtype': 'RANDOM' } full_url = scrape_url + '&'.join( ['{0}={1}'.format(key, val) for key, val in params.iteritems()]) res = requests.get(full_url) # process res data res_tree = ElementTree.fromstring(res.content) quote_text = res_tree.find('result').find('quote').text quote_author = res_tree.find('result').find('author').text # create quote model instance quote = Quote.create(quote_text=quote_text.strip(), author=quote_author.strip()) # store quote quote.save()
def scrape_brainy(cls): brainyquote_base_url = 'https://www.brainyquote.com' # make api call scrape_url = 'https://www.brainyquote.com/api/rand_q' res = requests.get(scrape_url) # unescape the result before deserializing json result res_json_string = cls.unescape_string(res.text) # process res data try: quote_data = json.loads(res_json_string) except: ErrorLog.log_exception('json.loads() fail with res json str: ' + res_json_string) sys.exit() # create quote model instance quote = Quote.create(quote_text=quote_data['qt'].strip(), author=quote_data['an'].strip(), source_url=brainyquote_base_url + quote_data['q_url'].strip()) # store quote quote.save()
def delete(self, quoteId): bogey = Quote("", "", quoteId) try: self.quotes.remove(bogey) except: pass
def ca_nhan(): if "token" in session: user = session["token"] info = User.objects(username=user).first() att = Attribute.objects(username=user).first() hstr_list = All_history.objects(user=user) qt_list = Quote.objects(username=user) if request.method == "GET": return render_template("ca_nhan.html", info=info, att=att, quotes=qt_list, history=hstr_list) else: form = request.form quote = form["quote"] author = form["author"] if author == "": q = Quote(username=user, quote=quote) else: q = Quote(username=user, quote=quote, author=author) q.save() return render_template("ca_nhan.html", info=info, att=att, quotes=qt_list, history=hstr_list) else: return redirect(url_for("sign_in"))
async def random_(self, ctx): """Показать случайную цитату""" quote = Quote.select().order_by(fn.Random()).get() if not quote: return await ctx.send(f"В базе цитат пусто") message = f'Автор: **{self.bot.get_user(quote.author_id).name}**\n' \ f' - *"{quote.text}"*' await ctx.send(message)
async def list_(self, ctx): """Показать список всех цитат""" quotes = tuple(Quote.select()) if not quotes: return await ctx.send(f"В базе цитат пусто") message = '\n\n'.join( f'Автор: **{self.bot.get_user(quote.author_id).name}**\n' f' - *"{quote.text}"*' for quote in quotes) await ctx.send(message)
def add_quote(author: Mention, quote, time, session=db_session) -> str: """Add a quote by the specified author""" if quote is None: raise QuoteException(QuoteError.BAD_FORMAT) if user_opted_out(author, session): raise QuoteException(QuoteError.OPTED_OUT) if author.is_id_type(): new_quote = Quote.id_quote(author.id, quote, time) else: new_quote = Quote.string_quote(author.string, quote, time) try: session.add(new_quote) session.commit() return str(new_quote.quote_id) except (ScalarListException, SQLAlchemyError) as e: session.rollback() logging.exception(e) raise QuoteException(QuoteError.DB_ERROR)
def save_quote(text, author, quoteTags): #saves the quote to db # todo: add logic to only save tags we have not seen before quote = Quote(author, text) db.session.add(quote) db.session.commit() for qTag in quoteTags: tag = Tag(qTag, quote.id) db.session.add(tag) # commit all the information db.session.commit()
def doAdd(quotes): logging.debug("Received doAdd command.") saying = verify("What is the quote?") if saying == COMMAND_ABORT: return author = verify("Who said it?") if author == COMMAND_ABORT: return newQuote = Quote( saying, author ) logging.debug( "Adding quote <%s>." % newQuote ) quotes.add( newQuote )
def __scraping_task(self): date_now = datetime.datetime.now() list_quote = [] print(f'Initializing capture at {date_now}') for stock in self.__stocks: print(f'Getting value from {stock.codigo}...') value = self.__scraping.get_stock_value(stock) list_quote.append(Quote(stock.codigo, date_now, value)) Mongo().insert_quotes(list_quote) print('Values inserted in MongoDB database')
async def remove_(self, ctx, *, quote_text: str): """Удалить цитату из базы""" if not quote_text: return await ctx.send( f"**{ctx.author.name}**, что ты мне прислал? После команды отправь цитату, которую надо удалить!" ) deleted = bool( Quote.delete().where(Quote.text == quote_text).execute()) if not deleted: return await ctx.send( f'Цитата _"{quote_text}"_ **не найдена** базе.') return await ctx.send(f'Цитата _"{quote_text}"_ **удалена** из базы.')
async def add_(self, ctx, *, quote_text: str): """Добавить цитату в базу""" if not quote_text: return await ctx.send( f"**{ctx.author.name}**, что ты мне прислал? Используй !help цитаты" ) quote, created = Quote.get_or_create(author_id=ctx.author.id, text=quote_text) if created: return await ctx.send( f'**{ctx.author.name}** добавил цитату _"{quote_text}"_.') return await ctx.send( f'Цитата _"{quote_text}"_ (**{ctx.author.name}**) уже есть в базе.' )
def test_getLastSaid(self): self.assertEqual( \ self.quotelist.quotes[0], \ self.quotelist.getLastSaid() \ ) # Any time we add a new quote, it should be the most recently said time.sleep(0.01) self.quotelist.add( Quote("Hello again", "Someone else") ) self.assertEqual( \ self.quotelist.quotes[1], \ self.quotelist.getLastSaid() \ ) self.quotelist.quotes[0].say() self.assertEqual( \ self.quotelist.quotes[0], \ self.quotelist.getLastSaid() \ )
class TestQuote(unittest.TestCase): def setUp(self): self.newQuote = Quote("Hello World!", "My Computer") def test_constructor(self): self.assertEqual(self.newQuote.say(), "Hello World! said My Computer") def test_lastSaidIsUpdating(self): initLastSaid = self.newQuote.getLastSaid() time.sleep(0.01) self.newQuote.say() self.assertNotEqual(initLastSaid, self.newQuote.getLastSaid()) def test_lastSaidIsInPast(self): self.newQuote.say() time.sleep(0.01) self.assertTrue(self.newQuote.getLastSaid() < time.time())
def scrape_forismatic(cls): # make api call scrape_url = 'http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en' res = requests.get(scrape_url) # unescape the result before deserializing json result res_json_string = cls.unescape_string(res.text) # process res data try: quote_data = json.loads(res_json_string) except: ErrorLog.log_exception('json.loads() fail with res json str: ' + res_json_string) sys.exit() # create quote model instance quote = Quote.create(quote_text=quote_data['quoteText'].strip(), author=quote_data['quoteAuthor'].strip(), source_url=quote_data['quoteLink'].strip()) # store quote quote.save()
def __add_new_quote(text): quote = Quote.make_quote(text).save() return f'The quote "{quote.text}" has been saved.'
def get(self, id): return Quote.find_by_id(id).json()
with open( fileName,'rb' ) as f: quotes = pickle.load( f ) logging.debug("Loaded quotes successfully.") except IOError: logging.warn("Unable to load <%s>." % fileName) """ """ quotes.add( Quote( \ "", \ "" \ )) """ quotes.add( Quote( \ "By providing more opportunities for people to feel part of something bigger than themselves, we can more strongly stitch together the fabric of our nation.", \ "MacKenzie Moritz" \ )) quotes.add( Quote( \ "Service is the American way to change America.", \ "Shirley Sagawa" \ )) quotes.add( Quote( \ "Through a serious commitment to bridging our differences and restoring our confidence in solving big challenges together, America can reignite the energy needed to make our country what it can be.", \ "General Stanley McChrystal" \ )) quotes.add( Quote( \ "We need to think bigger to leverage the human capital represented by the half a million young adults who want to serve.", \ "Shirley Sagawa" \
def setUp(self): self.quotelist = QuoteList() self.quotelist.add( Quote("Hi", "Me") )
def setUp(self): self.newQuote = Quote("Hello World!", "My Computer")