Creating endpoints inside an endpoint in fastapi - python

suppose there as an audio server, you can upload Songs, podcasts, or Audiobook. So in the create endpoint i have created 4 endpoints, so i have put an condition if the audio_type is a song, return all audio of that type but unfortunately this return null
#app.get('/audio/{audio_type}')
def show_all(audio_type):
if audio_type == "Songs":
#app.get("audio/song")
def all(db: Session = Depends(database.get_db)):
songs = db.query(models.Song).all()
print("songs = ", songs)
return songs
elif audio_type == "podcast":
#app.get('audio/podcast')
def all(db: Session = Depends(database.get_db)):
podcast = db.query(models.Podcast).all()
return podcast
elif audio_type == "audiobook":
#app.get('audio/audiobook')
def all(db: Session = Depends(database.get_db)):
audiobook = db.query(models.Audiobook).all()
return audiobook
else:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f' {audio_type} - audio type is not valid')

You are defeating the purpose of an API with your implementation.
For such an implementation, try passing the value as an argument to your API and based upon that you can bifurcate the flow.
def all(db: Session = Depends(database.get_db), audio_type):
if audio_type == "Songs":
songs = db.query(models.Song).all()
print("songs = ", songs)
return songs
elif audio_type == "podcast":
podcast = db.query(models.Podcast).all()
return podcast
elif audio_type == "audiobook":
audiobook = db.query(models.Audiobook).all()
return audiobook
else:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f' {audio_type} - audio type is not valid')
#app.get('/audio')
def show_all(audio_type: str):
return all(Depends(database.get_db), audio_type):

Related

Tweepy Stream client Termination on button click

ive been trying to create a stream client using tweepy to fetch new tweets under a user-given hashtag. I've managed to achieve this using the following code successfully.
import tweepy
class IDPrinter(tweepy.StreamingClient):
def on_tweet(self,tweet):
#now = datetime.now()
#current_time = now.strftime("%H:%M:%S")
#print("Current Time =", current_time)
print(f"{tweet.id} \n {tweet.created_at} \n {tweet.author_id} \n {tweet.text}")
#https://docs.tweepy.org/en/v3.4.0/streaming_how_to.html
def on_error(self, tweet_code):
if tweet_code == 420:
return False
def cleanUP(self,printer):
print("test")
rule_ids = []
rules = printer.get_rules()
if str(rules).find("id") == -1:
print(rules)
return
else:
for rule in rules.data:
rule_ids.append(rule.id)
if(len(rule_ids) > 0):
printer.delete_rules(rule_ids)
print("rules have been reset")
else:
print("no rules to delete")
def Caller(self,value,printer):
#print("test")
printer.add_rules(tweepy.StreamRule(f"#{value} lang:en -is:retweet"))
printer.filter(expansions="author_id", tweet_fields="created_at")
But I want the user to be able to stop the stream of new tweets whenever he wants to. Ive been testing the following code but I can't get the tweepy stream loop to terminate on button click. This is my current attempt but I can't understand why is not working.
def on_button_clicked(event):
global break_cicle
break_cicle = False
print("Button pressed: break_cicle:", break_cicle)
class IDPrinter(tweepy.StreamingClient):
def on_tweet(self,tweet):
print(f"{tweet.id} \n {tweet.created_at} \n {tweet.author_id} \n {tweet.text}")
#https://docs.tweepy.org/en/v3.4.0/streaming_how_to.html
def on_error(self, tweet_code):
if tweet_code == 420:
return False
def cleanUP(self,printer):
print("test")
rule_ids = []
rules = printer.get_rules()
if str(rules).find("id") == -1:
print(rules)
return
else:
for rule in rules.data:
rule_ids.append(rule.id)
if(len(rule_ids) > 0):
printer.delete_rules(rule_ids)
print("rules have been reset")
else:
print("no rules to delete")
def Call(self,value,printer):
while break_cicle:
button.on_click(on_button_clicked)
printer.add_rules(tweepy.StreamRule(f"#{value} lang:en -is:retweet"))
printer.filter(expansions="author_id", tweet_fields="created_at")
time.sleep(1)
printer = IDPrinter("bearer key")
printer.cleanUP(printer)
hashtag = input("Give a hashtag: ")
button = widgets.Button(description="STOP!")
output = widgets.Output()
display(button, output)
break_cicle = True
button.on_click(on_button_clicked)
threading.Thread(target=printer.Call(hashtag,printer)).start()
basically i tried to create a button which on event click will change the variable break_circle and terminate the while loop onside def call.

Chatting flask projects with pymongo

This is the first time t work with flask and pymongo. Anyone can tell my why and how to fix this problem ?
I had watched this video: https://www.youtube.com/watch?v=7Abxa0q4Vuk and use his code. However, it isn't work when i try to login.
It is a picture I captured when I tried to log in with an account had already register
This is the login_check code:
if(request.method == 'POST'):
req = request.form
req = dict(req)
print(req)
query = user_table.find({'uid', req['uid']})
flag = 0
temp = None
for x in query:
if(x['uid'] == req['uid']):
flag = 1
temp = x
break
if(flag == 1):
if(temp['password'] == req['password']):
return render_template('dashboard.html', uid = req['uid'])
else:
return render_template('invalid.html', message = 'incorrect password')
else:
return render_template('invalid.html', message = "User not registered")
return render_template('login.html')
This is the error:
filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping

discord.py discord_components interaction failed

I wanted to make a discord bot and one of his features is shop,
for shop menu I used discord components, It loops to a items file made in yaml and then append to a list in python, then make a embed message with that item and his options, with buttons for forward and back, when I click them they work but it take a while until they update and I receive "This interaction failed"
CODE:
with open('items.yaml', 'r') as yaml_file:
item_list_yaml = yaml.safe_load(yaml_file)
items = []
shop_items = []
for item in item_list_yaml:
items.append(item)
for item in items:
new_item_listed = {
'name':item_list_yaml[f'{item}']['name'],
'buy_price':item_list_yaml[f'{item}']['buy_price'],
'amount':item_list_yaml[f'{item}']['amount'],
'sell_price':item_list_yaml[f'{item}']['sell_price'],
'item_id':item_list_yaml[f'{item}']['item_id'],
'emoji':item_list_yaml[f'{item}']['emoji'],
}
copy = new_item_listed.copy()
shop_items.append(copy)
class Shop(commands.Cog):
def __init__(self, client):
self.client = client
self.cluster = MongoClient(DB)
cluster = MongoClient(DB)
self.collection = cluster.users.eco
DiscordComponents(client)
#commands.command(
name = "shop"
)
async def main_shop(self, ctx):
global position_in_shop_items
position_in_shop_items = 0
max_position_in_shop_items = len(shop_items)
def get_buttons(x, y, z):
if x == 0:
label = "->"
elif x == y:
label = "<-"
else:
if z == 1:
label = "->"
elif z == 3:
label = "<-"
return label
while True:
start_component = ([Button(style=ButtonStyle.grey, label="->"), Button(style=ButtonStyle.grey, label="<-")])
item = shop_items[position_in_shop_items]
if item['sell_price'] is None:
embed = discord.Embed(
title = "Shop",
description = f"""
{item['emoji']}**{item['name']}**
**Buy Price: `{item['buy_price']}`<:coins:872444592115568661>**
"""
)
elif item['buy_price'] is None:
embed = discord.Embed(
title = "Shop",
description = f"""
{item['emoji']}**{item['name']}**
**Sell Price: `{item['sell_price']}`<:coins:872444592115568661>**
"""
)
else:
embed = discord.Embed(
title = "Shop",
description = f"""
{item['emoji']}**{item['name']}**
**Buy Price: `{item['buy_price']}`<:coins:872444592115568661>**
**Sell Price: `{item['sell_price']}`<:coins:872444592115568661>**
"""
)
if position_in_shop_items == 0:
temp = await ctx.send(embed=embed, components = [Button(style=ButtonStyle.grey, label=get_buttons(position_in_shop_items, max_position_in_shop_items, 1))])
elif position_in_shop_items == max_position_in_shop_items:
try:
await temp.edit(embed=embed, components = [Button(style=ButtonStyle.grey, label=get_buttons(position_in_shop_items, max_position_in_shop_items, 3))])
except:
pass
else:
try:
await temp.edit(embed=embed, components = [[Button(style=ButtonStyle.grey, label="<-"), Button(style=ButtonStyle.grey, label="->")]])
except:
pass
response = await self.client.wait_for("button_click")
if response.component.label == "->":
position_in_shop_items +=1
elif response.component.label == "<-":
position_in_shop_items -=1
Discord expects a response to the created interaction, with discord components this is materialized by the Interaction.respond() method which is documented here.
You have several response methods, but if you just don't want to do anything, put 6 for the type parameter.
If you want to do something else, there are other possibilities documented here.

Alexa Skills Kit "Skill execution returned an exception for requestId" error

I'm very new to the Alexa Skills Kit. And I`ve been trying to make a simple music player skill on a web hosted server in https://www.pythonanywhere.com. When I try to make a request a
"SKILL_ENDPOINT_ERROR"
is captured in the device log with the following description:
"Skill execution returned an exception for requestId
amzn1.echo-api.request.e08ec414-0a30-4e95-87bb-28f315c8d4eb".
This is my skill request handler code:
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.utils import is_intent_name, is_request_type
from flask import Flask
from flask_ask_sdk.skill_adapter import SkillAdapter
from ask_sdk_model.ui import SimpleCard
app = Flask(__name__)
sb = SkillBuilder()
#VARIABLES
Current_song = ""
silent_mode = False
"""/////////////////////////
// Request Handlers //
////////////////////////"""
#Launch request
#sb.request_handler(can_handle_func=is_request_type("LaunchRequest"))
def launch_request_handler(handler_input):
speech_text = "What do you wish to play?"
return handler_input.response_builder.speak(speech_text).set_card(
SimpleCard("Hello World", speech_text)).set_should_end_session(
False).response
#Session Ended Request
#sb.request_handler(can_handle_func=is_request_type("SessionEndedRequest"))
def session_ended_request_handler(handler_input):
return handler_input.response_builder.response
"""/////////////////////////
// ASK Intent Handlers //
////////////////////////"""
#Help Intent
#sb.request_handler(can_handle_func=is_intent_name("AMAZON.HelpIntent"))
def help_intent_handler(handler_input):
speech_text = "You can ask me to play something on your server!"
return handler_input.response_builder.speak(speech_text).ask(
speech_text).set_card(SimpleCard(
"Wha can I do", speech_text)).response
#Stop Skill intent
#sb.request_handler(
can_handle_func=lambda handler_input:
is_intent_name("AMAZON.CancelIntent")(handler_input) or
is_intent_name("AMAZON.StopIntent")(handler_input))
def cancel_and_stop_intent_handler(handler_input):
speech_text = "Goodbye!"
return handler_input.response_builder.speak(speech_text).set_card(
SimpleCard("Hello World", speech_text)).response
#FallBack Intent
#sb.request_handler(can_handle_func=is_intent_name("AMAZON.FallbackIntent"))
def fallback_handler(handler_input):
speech = (
"I can't help you with that. "
"You can ask me to play music!")
reprompt = "You can ask me to play music!"
handler_input.response_builder.speak(speech).ask(reprompt)
return handler_input.response_builder.response
"""/////////////////////////
// Bot Intent Handlers //
////////////////////////"""
#Play Intent
#sb.request_handler(can_handle_func=is_intent_name("PlayIntent"))
def Play_intent_handler(handler_input):
song_value = handler_input.request_envelope.request.intent.slots["music"].value
if song_value:
speak_output = "Now playing {} on our server.".format(song_value)
Current_song = song_value
else:
speak_output = "I dont know what you want to play."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).ask(speak_output).set_card(SimpleCard("Playing {}...".format(song_value), speak_output))
return handler_input.response_builder.response
#Pause Intent
#sb.request_handler(can_handle_func=is_intent_name("PauseIntent"))
def Pause_intent_handler(handler_input):
speak_output = "Paused."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Pause", speak_output))
return handler_input.response_builder.response
#Loop Intent
#sb.request_handler(can_handle_func=is_intent_name("LoopIntent"))
def Loop_intent_handler(handler_input):
speak_output = "Song loop enabled."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Loop", speak_output))
return handler_input.response_builder.response
#Restart Intent
#sb.request_handler(can_handle_func=is_intent_name("RestartIntent"))
def Restart_intent_handler(handler_input):
speak_output = "Restarting current song"
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Restart", speak_output))
return handler_input.response_builder.response
#Resume Intent
#sb.request_handler(can_handle_func=is_intent_name("ResumeIntent"))
def Resume_intent_handler(handler_input):
speak_output = "Resumed."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Resume", speak_output))
return handler_input.response_builder.response
#Now Playing Intent
#sb.request_handler(can_handle_func=is_intent_name("NowPlayingIntent"))
def Now_Playing_intent_handler(handler_input):
if Current_song:
speak_output = "Now playing {}.".format(Current_song)
else:
speak_output = "There is nothing playing at the moment"
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Now Playing", speak_output))
return handler_input.response_builder.response
#Print Intent
#sb.request_handler(can_handle_func=is_intent_name("PrintIntent"))
def Print_intent_handler(handler_input):
speak_output = "Printed."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Print", speak_output))
return handler_input.response_builder.response
#Remove Number Intent
#sb.request_handler(can_handle_func=is_intent_name("RemoveNumIntent"))
def Remove_Num_intent_handler(handler_input):
num_value = handler_input.request_envelope.request.intent.slots["MusicNum"].value
if num_value:
speak_output = "Removed song number {} from queue".format(num_value)
else:
speak_output = "There is no song in number {}".format(num_value)
if silent_mode == False:
handler_input.response_builder.speak(speak_output).ask(speak_output).set_card(SimpleCard("Remove", speak_output))
return handler_input.response_builder.response
#Remove Position Intent
#sb.request_handler(can_handle_func=is_intent_name("RemovePosIntent"))
def Remove_Pos_intent_handler(handler_input):
pos_value = handler_input.request_envelope.request.intent.slots["MusicPos"].value
if pos_value:
speak_output = "Removed {} song from queue.".format(pos_value)
else:
speak_output = "There is no {} song in queue.".format(pos_value)
if silent_mode == False:
handler_input.response_builder.speak(speak_output).ask(speak_output).set_card(SimpleCard("Remove", speak_output))
return handler_input.response_builder.response
#Remove All Intent
#sb.request_handler(can_handle_func=is_intent_name("RemoveALLIntent"))
def Remove_All_intent_handler(handler_input):
speak_output = "All songs removed from queue"
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Remove", speak_output))
return handler_input.response_builder.response
#Back Intent
#sb.request_handler(can_handle_func=is_intent_name("BackIntent"))
def Back_intent_handler(handler_input):
speak_output = "Went back a song in queue."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Back", speak_output))
return handler_input.response_builder.response
#Skip Intent
#sb.request_handler(can_handle_func=is_intent_name("SkiptIntent"))
def Skip_intent_handler(handler_input):
speak_output = "Skipped."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Skip", speak_output))
return handler_input.response_builder.response
#Shuffle Intent
#sb.request_handler(can_handle_func=is_intent_name("ShuffleIntent"))
def Shuffle_intent_handler(handler_input):
speak_output = "Shuffled queue."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Shuffle", speak_output))
return handler_input.response_builder.response
#Skip to number Intent
#sb.request_handler(can_handle_func=is_intent_name("SkipToNumIntent"))
def Skip_To_Num_intent_handler(handler_input):
num_value = handler_input.request_envelope.request.intent.slots["MusicNum"].value
if num_value:
speak_output = "Skiped to song number {}.".format(num_value)
else:
speak_output = "There is no {} song in queue.".format(num_value)
if silent_mode == False:
handler_input.response_builder.speak(speak_output).ask(speak_output).set_card(SimpleCard("Skip To", speak_output))
return handler_input.response_builder.response
#Skip to position Intent
#sb.request_handler(can_handle_func=is_intent_name("SkipToPosIntent"))
def Skip_To_Pos_intent_handler(handler_input):
pos_value = handler_input.request_envelope.request.intent.slots["MusicPos"].value
if pos_value:
speak_output = "Skiped to {} song in queue.".format(pos_value)
else:
speak_output = "There is no {} song in queue.".format(pos_value)
if silent_mode == False:
handler_input.response_builder.speak(speak_output).ask(speak_output).set_card(SimpleCard("Skip To", speak_output))
return handler_input.response_builder.response
#Loop queue Intent
#sb.request_handler(can_handle_func=is_intent_name("LoopQueueIntent"))
def Loop_Queue_intent_handler(handler_input):
speak_output = "Looped queue."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Loop Queue", speak_output))
return handler_input.response_builder.response
#Silent Mode Intent
#sb.request_handler(can_handle_func=is_intent_name("SilentModeIntent"))
def Silent_Mode_intent_handler(handler_input):
silent_mode = True
return handler_input.response_builder.response
#Disconnect Intent
#sb.request_handler(can_handle_func=is_intent_name("DisconnectIntent"))
def Disconnect_intent_handler(handler_input):
speak_output = "Disconnected."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Disconnect", speak_output))
return handler_input.response_builder.response
sa = SkillAdapter(skill=sb.create(), skill_id="amzn1.ask.skill.e5e95d9a-6047-41aa-96f1-879b88421432", app=app)
"""/////////////////////////
// Exception Handlers //
////////////////////////"""
#Exception Handler
#sb.exception_handler(can_handle_func=lambda i, e: True)
def all_exception_handler(handler_input, exception):
speech = "Sorry, there was some problem. Please try again!!"
handler_input.response_builder.speak(speech).ask(speech)
return handler_input.response_builder.response
#app.route("/")
def invoke_skill():
return sa.dispatch_request()
I first assumed the problem was that I didn't have an Exeption Handler, but there was no change in the result since I implemented one.
Has anyone solved this issue or has any idea what my code is missing?

Not able to break from loop while running a Telegram Bot

I am creating a Telegram Bot using pyTelegramBotAPI that sends real-time updates of ongoing cricket matches. I want to break the loop whenever the user enters the "/stop" command. I've looked up various sources and also tried several methods to achieve the same but all in vain. The loop continues to iterate. The closest I've reached is by exiting the program by raising an error. Also, while inside the loop, the getUpdates method always returns an empty list. I've also written an issue for the same on GitHub.
def loop(match_url):
prev_info = ""
flag = 1
#continuously fetch data
while flag:
response = requests.get(match_url)
info = response.json()['score']
#display only when the score updates
if str(info) != prev_info:
prev_info = str(info)
send_msg(info)
else:
pass
send_msg(info)
#this handler needs to be fixed
#bot.message_handler(commands=['stop', 'end'])
def stop(message):
#code to break the loop
flag = 0
return
Since this was not working, I willingly used this wrong method:
while flag:
response = requests.get(match_url)
info = response.json()['score']
if str(info) != prev_info:
prev_info = str(info)
send_msg(info)
else:
pass
send_msg(info)
#bot.message_handler(commands=['stop', 'end'])
def stop(message):
bot.polling.abort = True #an arbitrary function that raises error and exits the program
Here's the whole code. I've also added my GitHub link of this code:
import requests, json, telebot
token = <TOKEN>
bot = telebot.TeleBot(token)
#parsing data from cricapi.com
def live_matches():
#here I'm using the KEY obtained from cricapi.com
curr_matches_url = "https://cricapi.com/api/cricket?apikey=<KEY>"
curr_matches = requests.get(curr_matches_url)
match_data = curr_matches.json()['data']
global unique_id_arr, score_arr
unique_id_arr, score_arr = [], []
match_details = ""
for i in match_data:
unique_id_arr.append(i["unique_id"])
for i in range(len(match_data)):
score_arr.append(match_data[i]["title"])
score_arr[i] += "\n"
match_details += str(i+1) + ". "
match_details += score_arr[i]
send_msg(match_details)
def send_msg(msg):
url2 = 'https://api.telegram.org/bot'+token+'/sendMessage'
data = {'chat_id': chat_id, 'text': msg}
requests.post(url2, data).json()
#bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.reply_to(message, "Howdy, how are you doing?")
global chat_id
chat_id = message.chat.id
msg = bot.reply_to(message, "Welcome to test project\nEnter the match number whose updates you want to receive")
live_matches()
bot.register_next_step_handler(msg, fetch_score)
def fetch_score(message):
chat_id = message.chat.id
match_no = message.text
#checking if the number entered is present in the displayed list
if not match_no.isdigit():
msg = bot.reply_to(message, 'Error1!\nSelect a no. from the above list only')
return bot.register_next_step_handler(msg, fetch_score)
elif 1 <= int(match_no) <= len(score_arr):
unique_id = unique_id_arr[int(match_no)-1]
global match_url
#get the data of the desired match
match_url = "https://cricapi.com/api/cricketScore?unique_id="+unique_id+"&apikey=<KEY>"
loop(match_url)
else:
msg = bot.reply_to(message, "Error2!\nSelect a no. from the above list only")
return bot.register_next_step_handler(msg, fetch_score)
def loop(match_url):
prev_info = ""
flag = 1
#continuously fetch data
while flag:
response = requests.get(match_url)
info = response.json()['score']
#display only when the score updates
if str(info) != prev_info:
prev_info = str(info)
send_msg(info)
else:
pass
send_msg(info)
#this handler needs to be fixed
#bot.message_handler(commands=['stop', 'end'])
def stop(message):
#an arbitrary function that raises error and then exits
bot.polling.abort = True
bot.polling()
"""
#currently not using
def receive_msg():
url1 = 'https://api.telegram.org/bot'+token+'/getUpdates'
response = requests.get(url1)
text = response.json()['result']
if len(text) > 0:
user_msg = text[-1]['message']['text']
return user_msg
return text
"""
You are using telebot(pyTelegramBotAPI) package in the wrong way:
Why did you create your own function send_msg where there is already send_message method in telebot exists?
You are redeclaring your "stop" handler in the loop, which is wrong!
My suggestion to you is to learn how to use the pyTelegramBotAPI properly!
Here is a demonstration code, that solves your problem:
import telebot
from time import sleep
bot = telebot.TeleBot(BOT_TOKEN)
flag = 1
#bot.message_handler(commands=['loop'])
def loop(msg):
while flag:
bot.send_message(msg.chat.id, "ping")
sleep(1)
#bot.message_handler(commands=['stop', 'end'])
def stop(msg):
global flag
flag = 0
bot.send_message(msg.chat.id, "stopped")
bot.polling(none_stop=True)
Explanation:
Declared flag as a global variable and set it to 1
"loop" handler for starting the loop that sends you "ping" message every second
"stop" handler that changes flag to 0, which terminates your running loop

Categories

Resources