codeforces_core package#

Subpackages#

Submodules#

codeforces_core.account module#

class codeforces_core.account.LoginResult(html: str = '', csrf: str = '', ftaa: str = '', bfaa: str = '', uc: str = '', usmc: str = '', success: bool = False)[source]#

Bases: object

bfaa: str = ''#
csrf: str = ''#
ftaa: str = ''#
html: str = ''#
success: bool = False#
uc: str = ''#
usmc: str = ''#
async codeforces_core.account.async_fetch_logged_in(http: AioHttpHelperInterface, login_url='/enter?back=%2F', **kw) Tuple[bool, str][source]#

auto update token return bool(is_logged_in), html_data

async codeforces_core.account.async_login(http: AioHttpHelperInterface, handle: str, password: str, login_url='/enter?back=%2F', **kw) LoginResult[source]#

This method will use http for login request, and is_user_logged_in() for login check

Parameters:
  • handle – Codeforces handle

  • password – Codeforces password

Returns:

if it is successful post and logged

Examples:

import asyncio
from codeforces_core.account import async_login, is_user_logged_in
from codeforces_core.httphelper import HttpHelper

async def demo():
  # http = HttpHelper(token_path='/tmp/cache_token', cookie_jar_path='/tmp/cache_cookie_jar')
  http = HttpHelper(token_path='', cookie_jar_path='')
  await http.open_session()
  result = await async_login(http=http, handle='<handle>', password='<password>')
  assert(result.success)

  html_data = await http.async_get('https://codeforces.com')
  assert(is_user_logged_in(html_data))

  await http.close_session()

asyncio.run(demo())
codeforces_core.account.extract_channel(html_data: str, logger: Optional[Logger] = None) Tuple[str, str, str, str, str, str, str][source]#
codeforces_core.account.is_user_logged_in(html_data: str) bool[source]#

codeforces_core.constants module#

codeforces_core.contest_list module#

class codeforces_core.contest_list.CodeforcesUser(name: str, title: str, class__: str, profile: str)[source]#

Bases: object

class__: str#
name: str#
profile: str#
title: str#
class codeforces_core.contest_list.ContestList(upcomming: List[codeforces_core.contest_list.ContestListItem], history: List[codeforces_core.contest_list.ContestListItem])[source]#

Bases: object

history: List[ContestListItem]#
upcomming: List[ContestListItem]#
class codeforces_core.contest_list.ContestListItem(id: int, title: str, authors: List[codeforces_core.contest_list.CodeforcesUser], start: int, length: str, participants: str, upcoming: bool, registered: bool, Div: List[str])[source]#

Bases: object

Div: List[str]#
authors: List[CodeforcesUser]#
id: int#
length: str#
participants: str#
registered: bool#
start: int#
title: str#
upcoming: bool#
async codeforces_core.contest_list.async_contest_list(http: AioHttpHelperInterface, page: int = 1, **kw) ContestList[source]#

This method will use http for get contests page, you can both login or not login

Parameters:

page – the page in url

Returns:

the result

Examples:

import asyncio
from codeforces_core.httphelper import HttpHelper
from codeforces_core.contest_list import async_contest_list

async def demo():
  # http = HttpHelper(token_path='/tmp/cache_token', cookie_jar_path='/tmp/cache_cookie_jar')
  http = HttpHelper(token_path='', cookie_jar_path='')
  await http.open_session()
  # you can login before get list
  result = await async_contest_list(http=http)
  for c in result.upcomming[:5]:
      print(c)
  for c in result.history[:5]:
      print(c)
  await http.close_session()

asyncio.run(demo())
async codeforces_core.contest_list.async_solved_count(http: AioHttpHelperInterface, solved_path: str)[source]#
codeforces_core.contest_list.ddhhmm2seconds(length: str) int[source]#
codeforces_core.contest_list.is_contest_running(item: ContestListItem) bool[source]#
codeforces_core.contest_list.parse_contest_list(raw_contests: ElementBase, upcoming: bool, **kw) List[ContestListItem][source]#
codeforces_core.contest_list.parse_contest_list_page(html_str: str, **kw) ContestList[source]#
codeforces_core.contest_list.parse_div(title: str) List[str][source]#

codeforces_core.contest_meta module#

class codeforces_core.contest_meta.ContestMeta(id: str = '', url: str = '', problems: List[codeforces_core.contest_meta.ProblemMeta] = <factory>)[source]#

Bases: object

id: str = ''#
problems: List[ProblemMeta]#
url: str = ''#
class codeforces_core.contest_meta.ContestPage(id: str, url: str, title: str, problems: List[codeforces_core.contest_meta.ProblemMeta], materials: List[codeforces_core.contest_meta.Materials])[source]#

Bases: object

id: str#
materials: List[Materials]#
problems: List[ProblemMeta]#
title: str#
url: str#
class codeforces_core.contest_meta.E_STATUS(value)[source]#

Bases: str, Enum

An enumeration.

AC = 'AC'#
ERROR = 'ERROR'#
NOT_SUBMITTED = ''#
class codeforces_core.contest_meta.Materials(text: str, url: str)[source]#

Bases: object

text: str#
url: str#
class codeforces_core.contest_meta.ProblemMeta(id: str = '', url: str = '', name: str = '', passed: str = '', status: codeforces_core.contest_meta.E_STATUS = <E_STATUS.NOT_SUBMITTED: ''>, time_limit_msec: int = 0, memory_limit_kb: int = 0, contest_id: str = '')[source]#

Bases: object

contest_id: str = ''#
id: str = ''#
memory_limit_kb: int = 0#
name: str = ''#
passed: str = ''#
status: E_STATUS = ''#
time_limit_msec: int = 0#
url: str = ''#
class codeforces_core.contest_meta.Questions(when: str, Q: str, A: str)[source]#

Bases: object

A: str#
Q: str#
when: str#
async codeforces_core.contest_meta.async_contest_meta(http: AioHttpHelperInterface, contest_id: str, **kw) ContestPage[source]#

This method will use http to request /contest/<contest_id>, and parse to struct result

Parameters:
  • http – AioHttpHelperInterface

  • contest_id – contest id in url

Returns:

parsed structured result

Examples:

import asyncio
from codeforces_core.httphelper import HttpHelper
from codeforces_core.contest_meta import async_contest_meta

async def demo():
  # http = HttpHelper(token_path='/tmp/cache_token', cookie_jar_path='/tmp/cache_cookie_jar')
  http = HttpHelper(token_path='', cookie_jar_path='')
  await http.open_session()
  # you can login before request
  result = await async_contest_meta(http=http, contest_id = '1779')
  print(result.id)
  print(result.title)
  print(result.url)
  print(result.problems)
  print(result.materials)
  await http.close_session()

asyncio.run(demo())
codeforces_core.contest_meta.parse_materials(resp: str) List[Materials][source]#
codeforces_core.contest_meta.parse_problems(resp: str) List[ProblemMeta][source]#

codeforces_core.contest_register module#

class codeforces_core.contest_register.RegisterResult(title: str = '', msg: codeforces_core.contest_register.RegisterResultMsg = <RegisterResultMsg.Empty: ''>)[source]#

Bases: object

msg: RegisterResultMsg = ''#
title: str = ''#
class codeforces_core.contest_register.RegisterResultMsg(value)[source]#

Bases: str, Enum

An enumeration.

AlreadyRegistered = 'You are already registered for the contest'#
Empty = ''#
HaveBeenRegistered = 'You have been successfully registered'#
NoRegistrationIsOpenedNow = 'No registration is opened now'#
async codeforces_core.contest_register.async_register(http: AioHttpHelperInterface, contest_id: str, **kw) RegisterResult[source]#

This method will use http for register request, you need login before

Parameters:

contest_id – Codeforces contest_id in url

Returns:

the result

Examples:

import asyncio
from codeforces_core.account import async_login
from codeforces_core.httphelper import HttpHelper
from codeforces_core.contest_register import async_register, RegisterResultMsg

async def demo():
  # http = HttpHelper(token_path='/tmp/cache_token', cookie_jar_path='/tmp/cache_cookie_jar')
  http = HttpHelper(token_path='', cookie_jar_path='')
  await http.open_session()
  result = await async_login(http=http, handle='<handle>', password='<password>')
  assert(result.success)
  result = await async_register(http=http,contest_id='1811')
  print(result)
  # assert result.msg == RegisterResultMsg.HaveBeenRegistered
  # assert result.msg == RegisterResultMsg.AlreadyRegistered
  # assert result.msg == RegisterResultMsg.NoRegistrationIsOpenedNow
  await http.close_session()

asyncio.run(demo())

codeforces_core.contest_standing module#

class codeforces_core.contest_standing.Standing(head: List[str], rows: List[codeforces_core.contest_standing.StandingRow], url: str = '')[source]#

Bases: object

head: List[str]#
rows: List[StandingRow]#
url: str = ''#
class codeforces_core.contest_standing.StandingProblem(id: str = '', score: str = '', time: str = '')[source]#

Bases: object

id: str = ''#
score: str = ''#
time: str = ''#
class codeforces_core.contest_standing.StandingRow(rank: str = '', who: str = '', passed: Optional[str] = None, score: str = '', hack: str = '', penalty: str = '', problems: List[codeforces_core.contest_standing.StandingProblem] = <factory>)[source]#

Bases: object

hack: str = ''#
passed: Optional[str] = None#
penalty: str = ''#
problems: List[StandingProblem]#
rank: str = ''#
score: str = ''#
who: str = ''#
async codeforces_core.contest_standing.async_common_standing(http: AioHttpHelperInterface, contest_id: str, page: str = '1', **kw) Standing[source]#

This method will use http to request /contest/<contest_id>/standings/page/<page>, and parse to struct result

Parameters:
  • contest_id – contest id in url

  • page – pagination 1-index

Returns:

parsed structured result

Examples:

import asyncio
from codeforces_core.httphelper import HttpHelper
from codeforces_core.contest_standing import async_common_standing

async def demo():
  # http = HttpHelper(token_path='/tmp/cache_token', cookie_jar_path='/tmp/cache_cookie_jar')
  http = HttpHelper(token_path='', cookie_jar_path='')
  await http.open_session()
  result = await async_common_standing(http=http, contest_id='1779', page='2')
  print(result.head)
  print(len(result.rows))
  print(result.rows[3])
  await http.close_session()

asyncio.run(demo())
async codeforces_core.contest_standing.async_friends_standing(http: AioHttpHelperInterface, contest_id: str, **kw) Standing[source]#

This method will use http to request /contest/<contest_id>/standings/friends/true, and parse to struct result

Parameters:

contest_id – contest id in url

Returns:

parsed structured result

Examples:

import asyncio
from codeforces_core.account import async_login
from codeforces_core.httphelper import HttpHelper
from codeforces_core.contest_standing import async_friends_standing

async def demo():
  # http = HttpHelper(token_path='/tmp/cache_token', cookie_jar_path='/tmp/cache_cookie_jar')
  http = HttpHelper(token_path='', cookie_jar_path='')
  await http.open_session()
  result = await async_login(http=http, handle='<handle>', password='<password>')
  assert(result.success)
  result = await async_friends_standing(http=http, contest_id='1779')
  print(result.head)
  print(len(result.rows))
  print(result.rows[3])
  await http.close_session()

asyncio.run(demo())
codeforces_core.contest_standing.parseStandingHtml(html) Standing[source]#

codeforces_core.httphelper module#

class codeforces_core.httphelper.HttpHelper(cookie_jar_path: str = '', token_path: str = '', headers={'Accept': '*/*', 'Accept-Encoding': 'gzip', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'}, host='https://codeforces.com', **kw)[source]#

Bases: AioHttpHelperInterface

async async_get(url, headers=None, csrf=False)[source]#
async async_post(url, data, headers={'Accept': '*/*', 'Accept-Encoding': 'gzip', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'}, csrf=False, **kwargs: Any)[source]#
check_rcpc(html_data: str)[source]#
async close_session() None[source]#
cookie_jar: Optional[CookieJar] = None#
cookie_jar_path = ''#
create_form(form_data) FormData[source]#
get_tokens()[source]#
headers: Dict[str, str] = {}#
static load_tokens(token_path: str) Dict[str, Any][source]#
logger: Logger#
async open_session() ClientSession[source]#
session: Optional[ClientSession] = None#
token_path = ''#
tokens: Dict[str, str] = {}#
update_tokens(csrf: str, ftaa: str, bfaa: str, uc: str, usmc: str) None[source]#
async websockets(url: str, callback: Callable[[Any], Tuple[bool, Any]]) AsyncIterator[Any][source]#
exception codeforces_core.httphelper.RCPCRedirectionError[source]#

Bases: Exception

codeforces_core.httphelper.add_header(newhdr, headers: Dict[str, str]) Dict[str, str][source]#
async codeforces_core.httphelper.on_request_end(session, trace_request_ctx, params)[source]#

codeforces_core.kwargs module#

class codeforces_core.kwargs.ExtractResult(logger: logging.Logger)[source]#

Bases: object

logger: Logger#
codeforces_core.kwargs.extract_common_kwargs(**kwargs) ExtractResult[source]#

codeforces_core.language module#

class codeforces_core.language.Lang(text: str, value: str)[source]#

Bases: object

text: str#
value: str#
async codeforces_core.language.async_language(http: AioHttpHelperInterface, **kw) List[Lang][source]#

This method will use http to request /problemset/submit, and parse language options

Returns:

parsed structured result

Examples:

import asyncio
from codeforces_core.account import async_login
from codeforces_core.httphelper import HttpHelper
from codeforces_core.language import async_language

async def demo():
  # http = HttpHelper(token_path='/tmp/cache_token', cookie_jar_path='/tmp/cache_cookie_jar')
  http = HttpHelper(token_path='', cookie_jar_path='')
  await http.open_session()
  result = await async_login(http=http, handle='<handle>', password='<password>')
  assert(result.success)
  result = await async_language(http)
  for item in result:
    print(item)
  await http.close_session()

asyncio.run(demo())

codeforces_core.logging module#

codeforces_core.logging.create_logger(name, debug=False) Logger[source]#
codeforces_core.logging.has_level_handler(logger: Logger) bool[source]#

Check if there is a handler in the logging chain that will handle the given logger’s effective level.

codeforces_core.problem module#

class codeforces_core.problem.ParseProblemResult(status: codeforces_core.problem.ParseProblemResult.Status = <Status.NOTVIS: 'NOTVIS'>, title: str = '', test_cases: List[codeforces_core.problem.TestCase] = <factory>, id: str = '', oj: str = '', description: str = '', time_limit: str = '', mem_limit: str = '', url: str = '', html: str = '', file_path: str = '')[source]#

Bases: object

class Status(value)[source]#

Bases: str, Enum

An enumeration.

AC = 'AC'#
FAILED = 'FAILED'#
NOTVIS = 'NOTVIS'#
description: str = ''#
file_path: str = ''#
html: str = ''#
id: str = ''#
mem_limit: str = ''#
oj: str = ''#
status: Status = 'NOTVIS'#
test_cases: List[TestCase]#
time_limit: str = ''#
title: str = ''#
url: str = ''#
class codeforces_core.problem.ProblemInfo(title: str, level: str, time_limit_seconds: str, memory_limit_mb: str, desc: str, in_tc: List[str], out_tc: List[str], note: str)[source]#

Bases: object

desc: str#
in_tc: List[str]#
level: str#
memory_limit_mb: str#
note: str#
out_tc: List[str]#
time_limit_seconds: str#
title: str#
class codeforces_core.problem.TestCase(in_data: str, out_data: str)[source]#

Bases: object

in_data: str#
out_data: str#
async codeforces_core.problem.async_problem(http: AioHttpHelperInterface, contest_id: str, level: str, **kw) ParseProblemResult[source]#

This method will use http to request /contest/<contest_id>/problems, and parse to struct result

Parameters:
  • http – AioHttpHelperInterface

  • contest_id – contest id in url

Returns:

parsed structured result

Examples:

import asyncio
from codeforces_core.httphelper import HttpHelper
from codeforces_core.problem import async_problem

async def demo():
  # http = HttpHelper(token_path='/tmp/cache_token', cookie_jar_path='/tmp/cache_cookie_jar')
  http = HttpHelper(token_path='', cookie_jar_path='')
  await http.open_session()
  # you can login before request
  result = await async_problem(http=http, contest_id='1779', level='F')
  print(result)
  await http.close_session()

asyncio.run(demo())

codeforces_core.problems module#

class codeforces_core.problems.ProblemInfo(title: str, level: str, time_limit_seconds: str, memory_limit_mb: str, desc: str, in_tc: List[str], out_tc: List[str], note: str)[source]#

Bases: object

desc: str#
in_tc: List[str]#
level: str#
memory_limit_mb: str#
note: str#
out_tc: List[str]#
time_limit_seconds: str#
title: str#
class codeforces_core.problems.TestCase(in_data: str, out_data: str)[source]#

Bases: object

in_data: str#
out_data: str#
async codeforces_core.problems.async_problems(http: AioHttpHelperInterface, contest_id: str, **kw) List[ProblemInfo][source]#

This method will use http to request /contest/<contest_id>/problems, and parse to struct result

Parameters:
  • http – AioHttpHelperInterface

  • contest_id – contest id in url

Returns:

parsed structured result

Examples:

import asyncio
from codeforces_core.httphelper import HttpHelper
from codeforces_core.problems import async_problems

async def demo():
  # http = HttpHelper(token_path='/tmp/cache_token', cookie_jar_path='/tmp/cache_cookie_jar')
  http = HttpHelper(token_path='', cookie_jar_path='')
  await http.open_session()
  # you can login before request
  result = await async_problems(http=http, contest_id='1779')
  print(len(result))
  print(result[0])
  await http.close_session()

asyncio.run(demo())
codeforces_core.problems.extract_testcases(tags)[source]#

codeforces_core.submit module#

class codeforces_core.submit.SubmissionPageResult(id: str = '', url: str = '', verdict: str = '', time_ms: str = '', mem_bytes: str = '')[source]#

Bases: object

id: str = ''#
mem_bytes: str = ''#
time_ms: str = ''#
url: str = ''#
verdict: str = ''#
class codeforces_core.submit.SubmissionWSResult(source: Any = <factory>, submit_id: int = 0, contest_id: int = 0, title: str = '', msg: str = '', passed: int = 0, testcases: int = 0, ms: int = 0, mem: int = 0, date1: str = '', date2: str = '', lang_id: int = 0)[source]#

Bases: object

contest_id: int = 0#
date1: str = ''#
date2: str = ''#
lang_id: int = 0#
mem: int = 0#
ms: int = 0#
msg: str = ''#
passed: int = 0#
source: Any#
submit_id: int = 0#
testcases: int = 0#
title: str = ''#
async codeforces_core.submit.async_fetch_submission_page(http: AioHttpHelperInterface, problem_url: str, **kw) List[SubmissionPageResult][source]#
async codeforces_core.submit.async_submit(http: AioHttpHelperInterface, contest_id: str, level: str, file_path: str, lang_id: str, **kw) Tuple[str, str][source]#

This method will use http to post submit

Parameters:
  • http – AioHttpHelperInterface

  • ws_handler – function to handler messages

Returns:

(submission_id, html_text of contest/<contest id>/my )

Examples:

import asyncio
from codeforces_core.httphelper import HttpHelper
from codeforces_core.account import async_login
from codeforces_core.websocket import create_contest_ws_task
from codeforces_core.submit import async_submit, display_contest_ws

async def demo():
  # http = HttpHelper(token_path='/tmp/cache_token', cookie_jar_path='/tmp/cache_cookie_jar')
  http = HttpHelper(token_path='', cookie_jar_path='')
  await http.open_session()
  result = await async_login(http=http, handle='<handle>', password='<password>')
  assert(result.success)

  print('before submit')
  submit_id, resp = await async_submit(http, contest_id='1777', level='F', file_path='F.cpp', lang_id='73')
  print('submit id:',submit_id)

  # connect websocket before submit sometimes cannot receive message
  contest_task = create_contest_ws_task(http, contest_id='1777', ws_handler=display_contest_ws)
  print("contest ws created");

  try:
    result = await asyncio.wait_for(contest_task, timeout=30)
    print("ws is done, result:", result)
  except asyncio.TimeoutError:
    pass
  await http.close_session()

asyncio.run(demo())
codeforces_core.submit.display_contest_ws(result: Any) Tuple[bool, Any][source]#
codeforces_core.submit.parse_submit_status(html_page: str) List[SubmissionPageResult][source]#
codeforces_core.submit.transform_submission(data: Any) SubmissionWSResult[source]#

codeforces_core.url module#

codeforces_core.url.pid2split(problem_id) Tuple[str, str][source]#

problem id to [contest id, problem key]

pid2split(‘1843F2’) == [‘1843’,’F2’]

codeforces_core.url.pid2url(problem_id: str) str[source]#
codeforces_core.url.problem_url_parse(problem_url: str) Tuple[str, str][source]#

https://codeforces.com/contest/1740/problem/G

convert to

[‘1740’, ‘G’]

codeforces_core.util module#

codeforces_core.util.pop_element(t)[source]#
codeforces_core.util.show_message(resp)[source]#
codeforces_core.util.soup_find_bs4Tag(soup: Tag, *args, **kwargs) Tag[source]#
codeforces_core.util.typedxpath(el: HtmlElement, s: str) List[HtmlElement][source]#

codeforces_core.websocket module#

async codeforces_core.websocket.create_contest_ws_task_yield(http: AioHttpHelperInterface, contest_id: str, ws_handler: Callable[[Any], Tuple[bool, Any]], **kw) AsyncIterator[SubmissionWSResult][source]#

This method will use http to create contest specific websocket, and ws_handler to handle each ws message

Parameters:
  • http – AioHttpHelperInterface

  • contest_id – contest id in the url

  • ws_handler – function to handler messages

Returns:

the task which run ws

Examples:

See docstring of codeforces_core.submit.async_submit()

codeforces_core.websocket.display_ws(result: Any) Tuple[bool, Any][source]#

Module contents#