Python

6424 readers
15 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

📅 Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
💓 Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS
351
12
submitted 1 year ago* (last edited 1 year ago) by Devos to c/python
 
 

Hi Python enthusiastic! I'm excited to share my latest project! The Datalookup 🔍 library makes it easier to filter and manipulate your data. The module is inspired by the Django Queryset Api and it's lookups.

I'm actively seeking people to join in and help make this library even better! Whether you have ideas for new features, bug fixes, or improvements in documentation, anyone can contribute to Datalookup's development.

Github: https://github.com/pyshare/datalookup

352
 
 

I've tried using pythorhead

search_results = lemmy.search(post_url)

but I get

AttributeError: 'Lemmy' object has no attribute 'search'

I've also tried requesting it myself but I don't get any results from the API even when I get it when searching for the same URL from the web interface.

@backoff.on_exception(
    backoff.expo,
    requests.exceptions.RequestException,
    max_time=MAX_BACKOFF_TIME,
)
def search(instance: str, url: str) -> Dict[str, Any]:
    api = f"https://{instance}/api/v3/search"
    query = f"?q={url}"
    response = requests.get(api + query)

    if response.status_code == 200:
        res: Dict[str, Any] = response.json()
        return res
    else:
        return {}

This makes it look more difficult than what I expected. https://programming.dev/comment/50809

353
 
 

An exercise-driven course on Advanced Python Programming that was battle-tested several hundred times on the corporate-training circuit for more than a decade. Written by David Beazley, author of the Python Cookbook, 3rd Edition (O'Reilly) and Python Distilled (Addison-Wesley). Released under a Creative Commons license. Free of ads, tracking, pop-ups, newletters, and AI.

354
 
 

Well, it ain't pretty, but it works eh :)

355
13
Python SQLite Recipe (constvoidblog.wordpress.com)
submitted 1 year ago by [email protected] to c/python
 
 

A copy/pastable Db class to help people get started on using SQLite in python!

356
357
 
 

When I'm writing webscrapers I mostly just pivot between selenium (because the website is too "fancy" and definitely needs a browser) and pure requests calls (both in conjunction with bs4).

But when reading about scrapers, scrapy is often the first mentioned Python package. What am I missing out on if I'm not using it?

358
 
 

Note that I mean the open version VSCodium and not VSCode. Even after manually installing the Python and Pylance vsix files into Codium I wasn't getting the Pylance hints in the editor. I find them super useful for ersatz static typing and just general problems.

359
20
submitted 1 year ago by jnovinger to c/python
360
361
 
 

Inspired by FastAPI and Kombu, Propan was created to simplify Message Brokers' code writing and to provide a helpful development toolkit, which existed only in HTTP-frameworks world until now.

It's designed to create reactive microservices around Messaging.

It is a modern, high-level framework on top of popular specific Python brokers libraries, based on pydantic, FastAPI, and pytest concepts.

362
363
10
Python's "next" function (www.pythonmorsels.com)
submitted 1 year ago by jnovinger to c/python
 
 

I guess I knew the whole "you can't use next on iterables" in the sense that I've never tried it.

I TIL'd about the default value for next.

364
 
 

I was inspired to try writing my own Python script for Lemmy after seeing some other scripts on here and seeing Plemmy.

With this script, you can specify multiple accounts to have communities blocked on. You can also specify multiple instances to block all communities from.

This might be a little niche, but I wanted an easier way to block everything from some specific NSFW instances. This is my first "real" python scripting project, so any feedback is appreciated!

365
 
 

Version 0.30 adds a new notification system. Similar to desktop notifications, it displays a small window with a title and message (called a toast) for a pre-defined number of seconds.

366
 
 

I'm writing a python package that I would like to distribute as a standalone terminal app. The structure of the project folder is the following:

energy-monitor/
-- config/
-- doc/
-- tests/
-- energymonitor/
---- init.py -> (empty)
---- main.py -> def main()
---- data/
---- ..other packages..
-- project.toml

I'm using setuptools to generate a .tar.gz archive, some relevant parts of the project.toml file are:

[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"

[project]
name = "energy-monitor"
version = "0.0.1"

...

[tool.setuptools.packages.find]
where = ["energymonitor"]

[tool.setuptools.package-data]
data = ["data/*"]

[project.scripts]
energy-monitor = "energymonitor.main:main"

I generate the .tar.gz and the .whl files with the command python -m build, then I run pipx install path/to/energy-monitor.tar.gz. The installation is succesful, but when calling energy-monitor from the command line I get:

Traceback (most recent call last):
  File "/home/mattia/.local/bin/energy-monitor", line 5, in <module>
    from energymonitor.main import main
ModuleNotFoundError: No module named 'energymonitor'

Why is this happening? I was not able to find any helpful solution online. It's the first that I build a python package so sorry if the issue is trivial.

  • python version: 3.11.3
367
 
 

ok, so I've just started to learn python so very sorry for being a absolute dumbell. I'm doing some test stuff and noticed when I build and run my programs, they run yes, but they don't actually do anything. I've made sure to set the right language in sublime editor. perhaps it's something I've done wrong? when the console prints out the first question, i type in a number, but then nothing else happens. it seems to only print the first line and that's it. it's supposed to prompt the "second:" but it does nothing. I would really appreciate your help. thank you.

368
 
 

I just found this plotting library by JetBrains that has a grammar of graphics interface (like plotnine). This will make a nice alternative for matplotlib for my research.

369
 
 

At least I posted it to [email protected] first!

370
7
submitted 1 year ago* (last edited 1 year ago) by [email protected] to c/python
 
 

I have a use case where I'd like to store a handful of strings with static values, alongside my code that references them. The general reason for not hard coding them where they're called, is that I'd like to make it easy for the end user to customize and modify them.

Are there any suggestions or comments about the best ways to do this? Storing them in a python file as vars seems reasonable. I've also considered saving them as JSON, though I don't know if there's any benefit to that in this case.

Thoughts are appreciated.

371
 
 

I've found this answer but in another answer the header was different. So what is this correct? Is there anyway to know from the output whether or not I've authenticated correctly?

import requests

# Replace <personal-access-token> with your personal access token
headers = {
    'Authorization': 'Bearer <personal-access-token>',
}

url = 'https://api.github.com/repos/LemmyNet/lemmy/issues'

response = requests.get(url, headers=headers)

# Print the response content
print(response.content)
372
 
 

I've seen two approaches which I'm going to post in the comments to see which one is considered best. Feel free to suggest others.

373
 
 

I have done plenty of basic scripting for work, but this is my first "real" project, and wanted to see what real python experts think of it and see if there is anything I might be doing horribly wrong lol.

Im deploying documentation automatically here: https://ogs-python.dakotamarshall.net/

And the PyPI package is here: https://pypi.org/project/ogsapi/

I am very much a beginner, and its still very much a work in progress. Let me know if there is anything that could be drastically improved!

374
 
 

I won't know if this script works until I run it and see the errors but the comments won't start to generate until after all the posts so I can't debug that part until I've already created too much content.

import sqlite3
import requests
from pythorhead import Lemmy
import schedule
import time
import logging
from config import *

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s %(message)s",
    handlers=[logging.FileHandler("debug.log"), logging.StreamHandler()],
)


def initialize_database():
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS posts (
            github_url TEXT PRIMARY KEY,
            lemmy_post_id INTEGER,
            lemmy_post_name TEXT,
            lemmy_post_body TEXT
        )
    """)
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS comments (
            github_comment_id INTEGER PRIMARY KEY,
            lemmy_comment_id INTEGER,
            comment_user TEXT,
            comment_body TEXT
        )
    """)
    conn.commit()
    return conn


def initialize_lemmy_instance():
    lemmy = Lemmy(LEMMY_INSTANCE_URL)
    lemmy.log_in(LEMMY_USERNAME, LEMMY_PASSWORD)
    logging.info("Initialized Lemmy instance")
    return lemmy


def discover_community(lemmy, community_name):
    community_id = lemmy.discover_community(community_name)
    logging.info(f"Discovered community {community_name} with ID {community_id}")
    return community_id


def fetch_github_issues(repo):
    url = f"{GITHUB_API_BASE}/repos/{repo}/issues"
    headers = {"Accept": "application/vnd.github+json"}
    response = requests.get(url, headers=headers)
    logging.info(f"Fetched issues from {url}")
    return response.json()


def extract_issue_info(issue, repo):
    issue_url = issue["html_url"]
    issue_state = "[Closed]" if issue["state"] == "closed" else ""
    repo_abbr = "[BE]" if "lemmy" in repo else "[UI]"
    issue_title = f"{issue_state}{repo_abbr} {issue['title']} #{issue['number']}"
    issue_body = issue["body"]
    return issue_url, issue_title, issue_body


def post_issues_to_lemmy(lemmy, community_id, repo):
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    
    issues = fetch_github_issues(repo)
    for issue in issues:
        issue_url, issue_title, issue_body = extract_issue_info(issue, repo)
        
        cursor.execute("SELECT lemmy_post_id FROM posts WHERE github_url=?", (issue_url,))
        existing_post = cursor.fetchone()
        
        if not existing_post:
            post = lemmy.post.create(community_id, issue_title, url=issue_url, body=issue_body)["post_view"]["post"]
            lemmy_post_id = post["id"]
            lemmy_post_name = post["name"]
            lemmy_post_body = post["body"]
            cursor.execute("INSERT INTO posts (github_url, lemmy_post_id, lemmy_post_name, lemmy_post_body) VALUES (?, ?, ?, ?)", (issue_url, lemmy_post_id, lemmy_post_name, lemmy_post_body))
            conn.commit()
            logging.info(f"Posted issue {issue_title} to community {community_id}")


def fetch_github_comments(repo, issue_number):
    url = f"{GITHUB_API_BASE}/repos/{repo}/issues/{issue_number}/comments"
    headers = {"Accept": "application/vnd.github+json"}
    response = requests.get(url, headers=headers)
    logging.info(f"Fetched comments for issue #{issue_number}")
    return response.json()


def post_comments_to_lemmy(lemmy, post_id, repo, issue_number):
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    
    github_comments = fetch_github_comments(repo, issue_number)
    for comment in github_comments:
        github_comment_id = comment["id"]
        cursor.execute("SELECT lemmy_comment_id FROM comments WHERE github_comment_id=?", (github_comment_id,))
        existing_comment = cursor.fetchone()
        
        if not existing_comment:
            comment_user = comment["user"]["login"]
            comment_body = comment["body"]
            lemmy_comment_id = lemmy.comment.create(post_id, comment_body)["comment"]["id"]

            cursor.execute("INSERT INTO comments (github_comment_id, lemmy_comment_id, comment_user, comment_body) VALUES (?, ?, ?, ?)", (github_comment_id, lemmy_comment_id, comment_user, comment_body))
            conn.commit()
            logging.info(f"Posted comment {github_comment_id} to lemmy post {post_id}")


# Fetch the GitHub issue number and Lemmy post ID for each issue
def fetch_issue_data(repo):
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    cursor.execute("SELECT github_url, lemmy_post_id FROM posts WHERE github_url LIKE ?", (f"https://github.com/{repo}/issues/%",))
    issue_data = cursor.fetchall()
    return issue_data


def extract_issue_number(github_url):
    return int(github_url.split("/")[-1])


def main():
    logging.info("Running main function")
    initialize_database()
    lemmy = initialize_lemmy_instance()
    community_id = discover_community(lemmy, LEMMY_COMMUNITY_NAME)
    for repo in REPOSITORIES:
        post_issues_to_lemmy(lemmy, community_id, repo)
        issue_data = fetch_issue_data(repo)
        for github_url, lemmy_post_id in issue_data:
            issue_number = extract_issue_number
            post_comments_to_lemmy(lemmy, lemmy_post_id, repo, issue_number)


def run_periodically():
    main()
    schedule.every(2).hours.do(main)

    while True:
        schedule.run_pending()
        time.sleep(60)


if __name__ == "__main__":
    logging.info("Starting script")
    run_periodically()
375
view more: ‹ prev next ›