import json
from urllib.request import urlopen, Request
class Coincap():
"""parser module for the coincap API"""
@staticmethod
def format_float(f, i=3):
return float(("%."+str(i)+"f") % float(f))
def get_info(self, convert_numbers=True):
"""Get the currency table from the api.coincap.io/v2/assets
Returns:
tuple: (headers 1d list, content 2d list with rows and cols)
"""
url = "https://api.coincap.io/v2/assets"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0",
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Language": "ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3",
"X-Requested-With": "XMLHttpRequest",
}
opener = Request(url, headers = headers)
resp = urlopen(opener)
content = resp.read().decode("UTF-8")
j = json.loads(content)
data_items = j["data"]
ret_headers = (
"Name",
"Ticker",
"Price",
"Capitalization",
"Change percent in 24 h",
"Value 24 h",
"Value",
"Change 24 h",
"Change 7 d",
)
# attention, I have not found any changes in this API in seven days
ret_content = []
tmp_data = []
for ditem in data_items:
tmp_data.append(ditem["name"])
tmp_data.append(ditem["symbol"])
priceUsd = self.format_float(ditem["priceUsd"])
tmp_data.append(priceUsd if convert_numbers else str(priceUsd) + " $")
tmp_data.append(
self.format_float(ditem["marketCapUsd"], 1)
if convert_numbers
else str(self.format_float(ditem["marketCapUsd"], 1)) + " $"
)
tmp_data.append(
self.format_float(ditem["volumeUsd24Hr"])
if convert_numbers
else str(self.format_float(ditem["volumeUsd24Hr"])) + " $"
)
tmp_data.append(
self.format_float(ditem["supply"])
if convert_numbers
else str(self.format_float(ditem["supply"]))
)
tmp_data.append(
self.format_float(ditem["changePercent24Hr"], 2)
if convert_numbers
else str(self.format_float(ditem["changePercent24Hr"], 2)) + "%"
)
tmp_data.append(0.0 if convert_numbers else "0.0")
ret_content.append(tmp_data)
tmp_data = []
return (ret_headers, tuple(ret_content))
if __name__ == "__main__":
cc = Coincap()
headers, content = cc.get_info()
btc = content[0]
print(btc[1], btc[2])
import logging
import asyncio
q = asyncio.Queue()
async def a_difficult_task(some_arg):
print(f"task {some_arg} started")
await asyncio.sleep(120)
print(f"task {some_arg} ended")
async def worker():
while True:
try:
some_arg = await q.get()
await a_difficult_task(some_arg=some_arg)
except (KeyboardInterrupt, SystemExit, SystemError):
break
except Exception:
logging.exception("...")
finally:
q.task_done()
async def main():
asyncio.create_task(worker())
print("Adding tasks to queue")
for x in range(1, 7):
await q.put( x )
print("Tasks added to queue")
while True:
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(main())
import telebot
from telebot import types
a = 100
bot = telebot.TeleBot('токен ')
def make_buttons(a):
markup = types.InlineKeyboardMarkup()
markup.row_width = 1
markup.add(types.InlineKeyboardButton(text="click", callback_data="cb_minus_"+str(a)))
return markup
@bot.message_handler(commands=['start'])
def start(message):
bot.send_message(
message.chat.id,
text="Привет, {0.first_name}! жми кнопки)))".format(message.from_user),
reply_markup=make_buttons(a)
)
@bot.callback_query_handler(func=lambda call: print(call.data))
@bot.callback_query_handler(func=lambda call: call.data.startswith('cb_'))
def callback_query(call):
print(call.data)
_, op, digit = call.data.split("_")
digit=int(digit)
if op=="minus":
digit-=1
bot.edit_message_reply_markup(
call.message.chat.id,
call.message.id,
make_buttons(digit)
)
bot.answer_callback_query(call.id, str(digit), show_alert=True)
bot.polling(none_stop=True)
a = 4
b = -22
c = 1
a = a if a < 0 else 0
b = b if b < 0 else 0
c = c if c < 0 else 0
print(a + b + c)
# pip install selenium
import os
from pathlib import Path
from platform import system
from urllib.parse import urlparse
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
options = Options()
options.add_argument("--headless")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument("--disable-blink-features=AutomationControlled")
exec_path = os.path.join(os.getcwd(), 'driver', 'chromedriver.exe') if system() == "Windows" else \
os.path.join(os.getcwd(), 'driver', 'chromedriver')
driver = webdriver.Chrome(options=options, service=Service(log_path=os.devnull, executable_path=exec_path))
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
'source': '''
delete window.cdc_adoQpoasnfa76pfcZLmcfl_Array;
delete window.cdc_adoQpoasnfa76pfcZLmcfl_Promise;
delete window.cdc_adoQpoasnfa76pfcZLmcfl_Symbol;
'''
})
def screen_sait(url) -> None:
path = str(urlparse(url).hostname).replace(Path(str(urlparse(url).hostname)).suffix, ".png")
driver.get(url)
s = lambda x: driver.execute_script('return document.body.parentNode.scroll' + x)
driver.set_window_size(s('Width'), s('Height'))
driver.find_element(By.TAG_NAME, 'body').screenshot(path)
driver.close()
driver.quit()
screen_sait('https://codeby.net/')
class Person(BaseModel):
age: conint(ge=30)
class Config:
validate_assignment = True
validate_all = True
class FormModel(BaseModel):
first: Optional[bool] = False
second: Optional[bool] = False
third: Optional[bool] = False
something_there: str = "qwexdfg"
class Config:
validate_assignment = True
@validator("first", "second", "third")
def set_bool(cls, val):
return False if val is None else val
@validator("something_there")
def set_str(cls, val):
return "x" in val
>>> import requests
>>> views:int = requests.get("https://api.telegra.ph/getViews/testfhiasehilf-07-21?year=2023&month=7").json()["result"]["views"]
>>> print(views)
7
>>>
>>> import requests
>>> views:int = requests.get("https://api.telegra.ph/getViews/testfhiasehilf-07-21").json()["result"]["views"]
>>> print(views)
7
>>>