Send a formated list with pushover on python [duplicate] - python

This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 2 years ago.
I'm relatively new to python,
I built a webscraper that gets the top posts of a website and stores them in a list in python like this:
T = ["post1","post2","post3,"post4"]
To send the push notification with pushover I installed the pushover module that works like this:
from pushover import Pushover
po = Pushover("My App Token")
po.user("My User Token")
msg = po.msg("Hello, World!")
po.send(msg)
I want to send the list as a message with format, like this:
Top Posts:
1. post 1
2. post 2
3. post 3
4. post 4
I tried this:
msg = po.msg("<b>Top Posts:</b>\n\n1. "+T[0]+"\n"+"2. "+T[1]+"\n"+"3. "+T[2]+"\n"+"4. "+T[3]")
The above solution works, however the number of posts will be variable so that's not a viable solution.
What can I do to send the message with the correct formatting knowing that the number of posts in the list will vary from time to time?

Using str.join and a comprehension using enumerate:
msg = po.msg("<b>Top Posts:</b>\n\n" + '\n'.join(f'{n}. s {n}' for n, s in enumerate(T, 1)))

Related

Python - Requests module "response.text" [duplicate]

This question already has an answer here:
How to extract values from a Python request
(1 answer)
Closed 6 months ago.
How do I get a specific element from requests response.text
{"status":"success","data":{"id":30815925}}
im need to get ID from that output
You can import the json package and simply do
import json
id = json.loads(response.text)["data"]["id"]
This will convert response.text from a string to a python dictionary, and the id will be inside the variable id

How to unpack a list inside placeholder { } in python [duplicate]

This question already has answers here:
Print list without brackets in a single row
(14 answers)
Closed 1 year ago.
I have a list of strings, name, ignore_stock. I want to display it in a telegram bot message. Presently, I am displaying it like this:
update.message.reply_text(f'<b>Following stocks are ignored: {ignore_stock}</b>', parse_mode='HTML')
This displays the list like this: ['a','b','c'] inside the telegram bot message.
I want to display the list like this: a, b, c inside the telegram bot message without [ ] and ''. How do I do that?
thanks in advance
Try replacing {ignore_stock} with {",".join(ignore_stock)}

Is there a way to load a flask route based on the url [duplicate]

This question already has answers here:
Get a variable from the URL in a Flask route
(2 answers)
Closed 2 years ago.
So I have a Flask app and there's basically two versions of the URL: example.com/ and example.com/MhkQV
But the ending(MhkQV) will be randomized based on a database. (It could be hDjnY for example)
Can I load a certain flask route if example.com/MhkQV is sent?
Yes, you can accept random values like 'MhkQV', Here I am using the name variable which accepts any random value just after '/'. and you may use this value inside your function or just for redirecting your URL.
#app.route('/<name>')
def hello_name(name):
return "Hello {}!".format(name)

Python requests with timer and string replace [duplicate]

This question already has answers here:
Print to the same line and not a new line? [duplicate]
(19 answers)
Closed 3 years ago.
I am using an API where I can fetch data with. From the data output I am trying to get specific portions so I can place it nicely in a formatted text.
I want to fetch the data every 5 seconds, so I get fresh info. I do not want that the data is prompted below the output from the first run, but rather replace the current value(s) for the updated value(s).
As I'm pretty bad with python, I hope someone can give me some advice.
import requests
import threading
def dostuff()
threading.Timer(5.0, dostuff).start()
r = requests.get('https://api')
data = r.json()
print("Amount:", data['amount'])
print("Games played:", data['matches'])
dostuff()
This works fine. It just keeps posting the output under each other.
I wish to have everything static, except the data['amount'], and data['matches'], which should keep updating without actually posting it on newlines. I have tried resolving this by clearning the screen, but that is not the desired solution.
Just add end='\r' to your print statement:
import requests
import threading
import random
def dostuff():
threading.Timer(1.0, dostuff).start()
# replaced as actual api not posted
data = {
'amount': round(random.random(), 2),
"matches": round(random.random(), 2)
}
print("Amount: {} Games played: {}".format(
data['amount'],
data['matches']
), end='\r')
dostuff()

I want to return html in a flask route [duplicate]

This question already has answers here:
Python Flask Render Text from Variable like render_template
(4 answers)
Closed 5 years ago.
Instead of using send_static_file, I want to use something like html('<h1>content</h1>'), sort of like jsonify.
#app.route('/incorrect_pass')
def incorrect_pass():
return html('Incorrect password. Go back?')
Is what I want to do.
Never mind. Should've checked. Flask returns strings as html, so the html() isn't necessary above.
Why not just:
def html(content): # Also allows you to set your own <head></head> etc
return '<html><head>custom head stuff here</head><body>' + content + '</body></html>'
#app.route('/incorrect_pass')
def incorrect_pass():
return html('Incorrect password. Go back?')
# OR return 'Incorrect password. Go back?

Categories

Resources