Giter Site home page Giter Site logo

halfstackpgr / py-codeforces Goto Github PK

View Code? Open in Web Editor NEW
2.0 1.0 0.0 257 KB

๐Ÿ’ป Py-Codeforces is a super-fast and type-safe focused library to interact with Codeforces with two clients, asynchronous and synchronous. The fields are used as it is.

Home Page: https://codeforces.com/apiHelp

License: GNU General Public License v3.0

Python 100.00%
code codeforces codeforces-api coding-standards codingcommunity python typesafety

py-codeforces's Introduction

Py-Codeforce

Faster | Better | Type-Safe

Ruff Passing Package Static Badge

image

Py-Codeforces

Py-Codeforces is a high-performance and type-safe Python library designed for seamless interaction with Codeforces. It offers both asynchronous and synchronous client handlers, allowing developers to choose the appropriate method based on their requirements.

Key Features:

  1. Client Handlers:

    • Synchronous Handler: SyncMethod
    • Asynchronous Handler: AsyncMethod
  2. Functionality:

    Both client handlers offer the same set of functionalities, ensuring consistency and flexibility in usage.

  3. Authentication:

    To access user-related attributes, authentication must be enabled by setting the enable_auth parameter to True.

  4. API Documentation:

    This library is built entirely based on the official Codeforces API Documentation, ensuring reliability and adherence to best practices.

Example Usage:

Asynchronous usage:

import asyncio
import pycodeforces

async def main():
    api = pycodeforces.AsyncMethod()
    users = await api.get_user_info(handles="DmitriyH;Fefer_Ivan")
    # use `;` to add multiple parameters.
    async for user in users:
        print(user.avatar)

asyncio.run(main())

Synchronous usage:

import pycodeforces

async def main():
    get = pycodeforces.SyncMethod()
    users = get.get_user_info(handles="DmitriyH;Fefer_Ivan")
    # use `;` to add multiple parameters.
    for user in users:
        print(user.avatar)

Features

  • Is 100% type safe.
  • For customisation in types, a specific module abc has been provided within the head module.
  • Dual modes for specific requirements regarding auth. -- Can be enabled by passing a True to Method constructor

Uses:

  1. msgspec - for data validation and then serialisation.
  2. ruff - for linear code formatting and consistency.

Installation

Installing as a user:

pip install py-codeforce

Installing as a developer:

pip install py-codeforce[dev]

Open Source Contribution:

Want to contribute? Great! Check the Issues for getting to know about further updates and solutions to occurring problems. Maintain the type-checking as strict. Stack a PR to the production

Thank you for checking out the repo. Give it a star if you've found it worthy.

py-codeforces's People

Contributors

halfstackpgr avatar

Stargazers

 avatar Indrajeet Shelake avatar

Watchers

 avatar

py-codeforces's Issues

Invalid Signature while Authorization handshake with API

Status:

  • Needs help.

Issue related to Authorization.

  • The issue is regarding the authorization process of the website through API.
  • Both the Methods contain these parameters:
    • enable_auth which is a bool
    • auth_key which is a string.
    • secret which is a string as well.
    • time which is an int representing time in unix format.
  • While we pass these parameters to the method constructor. The error for Invalid Signature is being returned from the API.

Code where the problem is:

In AsyncMethod:

    def _generate_authorisation(
        self,
        end_point_url: str,
        method_name: t.Literal[
            "blogEntry.comments",
            "blogEntry.view",
            "contest.hacks",
            "contest.list",
            "contest.ratingChanges",
            "contest.standings",
            "contest.status",
            "problemset.problems",
            "problemset.recentStatus",
            "recentActions",
            "user.blogEntries",
            "user.friends",
            "user.info",
            "user.ratedList",
            "user.rating",
            "user.status",
        ],
    ) -> str:
        if self._auth_enabled is True:
            if not self._time:
                self._time = int(time.time())
            randon_six_digit_num = random.randint(111111, 999999)
            head = end_point_url.removeprefix(
                f"https://codeforces.com/api/{method_name}?"
            )
            to_hash = f"{randon_six_digit_num}/{method_name}?apiKey={self._auth_key}&{head}&time={self._time}#{self._secret}"
            hashed_string = (hashlib.sha512(to_hash.encode("utf8"))).hexdigest()
            final_url = f"https://codeforces.com/api/{method_name}?{head}&apiKey={self._auth_key}&time={self._time}&apiSig={randon_six_digit_num}{hashed_string}"
            return final_url
        else:
            return end_point_url

In SyncMethod:

    def _generate_authorisation(
        self,
        end_point_url: str,
        method_name: t.Literal[
            "blogEntry.comments",
            "blogEntry.view",
            "contest.hacks",
            "contest.list",
            "contest.ratingChanges",
            "contest.standings",
            "contest.status",
            "problemset.problems",
            "problemset.recentStatus",
            "recentActions",
            "user.blogEntries",
            "user.friends",
            "user.info",
            "user.ratedList",
            "user.rating",
            "user.status",
        ],
    ) -> str:
        if self._auth_enabled is True:
            if not self._time:
                self._time = int(time.time())
            randon_six_digit_num = random.randint(111111, 999999)
            head = end_point_url.removeprefix(
                f"https://codeforces.com/api/{method_name}?"
            )
            to_hash = f"{randon_six_digit_num}/{method_name}?apiKey={self._auth_key}&{head}&time={self._time}#{self._secret}"
            hashed_string = (hashlib.sha512(to_hash.encode("utf8"))).hexdigest()
            final_url = f"https://codeforces.com/api/{method_name}?{head}&apiKey={self._auth_key}&time={self._time}&apiSig={randon_six_digit_num}{hashed_string}"
            return final_url
        else:
            return end_point_url

To reproduce the error:

Asynchronous usage:

import asyncio
import pycodeforces

async def main():
    api = pycodeforces.AsyncMethod(enable_auth=True, auth_key="YOUR_AUTH_KEY", secret="YOUR SECRET")
    users = await api.get_user_info(handles="DmitriyH;Fefer_Ivan")
    # use `;` to add multiple parameters.
    async for user in users:
        print(user.avatar)

asyncio.run(main())

Synchronous usage:

import pycodeforces

async def main():
    get = pycodeforces.SyncMethod(enable_auth=True, auth_key="YOUR_AUTH_KEY", secret="YOUR SECRET")
    users = get.get_user_info(handles="DmitriyH;Fefer_Ivan")
    # use `;` to add multiple parameters.
    for user in users:
        print(user.avatar)

Reference to authorization with API:

In: Documentation

Ref:

image

Guessed Problem:

Hashing of apiSig. Or the way apiSig is hashed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.