Skip to main content

ImprovadoTest

Python back-end test task

Installation

pip install vkinfo

Usage


1. Generate access_token

Why do you need one:
Indicates you as the one who is trying to get information, and wether or not you are allowed to.

For example: If user has private account and only his friends can acccess their info, or their music tastes are very singular, so only you can see it. VK just needs to know whos asking, otherwise its kinda creepy.

How to get one:
command below will open VK auth page and ask to grant permessions for this app.

vkinfo token

Then, you'll be redirected to blank page. Copy access_token from url of this page.
https://oauth.vk.com/blank.html#access_token={your_token}&expires_in=BAN&user_id=BAN5

Congrats! This is your access token for the next 24 hours.

2. Run script

vkinfo run {access_token} {search_user_id}

Parameters


Global

  • log-path: Path for the log file.

Exporting

  • export-path: Path for the log file.
  • export-format: Format for the export (choices: csv | json | tsv).

Example


vkinfo run asfajhskaaalx 1478202 --format tsv --path ~/projects/lalareport --log-path ~/projects/lalalogs.log

Command above will: get friends list of user 1478202 using token asfajhskaaalx and save it as tsv file in ~/projects/lalareport.tsv and log file saved in ~/projects/lalalogs.log

Endpoints


VK API endpoints used

  • /method/friends.get
  • /method/stats.TrackVisitor
  • /method/users.get
  • /authorize

Дополнение


Модульность и структура

  • Проект имеет структуру файлов и распределение по функционалу.
    • config файл с константами по умолчанию
    • exceptions для кастомных исключений и их обработки
    • get_token может запускаться как main
    • vk_api создает собственный класс-сессию для текущего пользователя с основными параметрами, новый функционал легко добавить как метод класса.
    • папка util содержит вспомогательные функции, такие как обработка данных и export класс
  • Редактирование представленного и добавление нового функционала.
    • с помощью VkApiSess.method_execute() можно использовать любые(get) методы api vk + произвольные параметры, а не только friends.get
    • полученные данные имеют представление pandas.Dataframe и обрабатываются в util.parsers в зависимости от поствленной задачи
    • класс exporter получает на вход pandas.Dataframe и делает с ним всё что можно и нельзя

Чистые логи

  • Чтобы не пугать пользователя кучей страшных символов, логи делятся.
    • Те, что видны в консоли(info): отображают ход выполнения программы.
    • Дебаг, логи внешних модулей и полные описания ошибок записываются в файл.
  • То же самое с ошибками, адекватные люди не будут копаться в traceback'ах, поэтому все исключения вызывают SystemExit с коротким сообщением, а неадекватные могут посмотреть в лог файле.

Простая установка через pip

  • Проект загружен на PyPi для максимальной простоты установки

Оптимальный анализ данных

  • Для анализа данных выбрал pandas потому что он удобный, универсальный, гибкий и вообще клёвый.
  • Также выбор pandas обусловлен капом на друзей в 10к, для таких размеров это показалось оптимальным вариантом(подробнее в комментах vk_api.py). Но это вряд ли оптимальная стратегия для более массивных данных.

Замечания

  • Особо важные комменты на русском ибо понимание > понты

  • Писал и тестировал на wsl2 Ubuntu20.04

  • Во время получения токена(а точнее открытия браузера) есть косяк, но это никак не мешает работе скрипта и косяк только wsl

  • Не приспособлено и даже не запускалось на Windows

  • python3.8.10

Metadata

Release files for vkinfo 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for vkinfo 0.1.2
File Size Uploaded Provenance Actions
vkinfo-0.1.2.tar.gz 15.9 kB Without provenance Details for vkinfo-0.1.2.tar.gz

Release files / vkinfo-0.1.2.tar.gz

Download URL vkinfo-0.1.2.tar.gz
Size 15.9 kB
Tags Source
SHA-256 checksum
How to use checksums
7bbd1f4ae407d3ace5e94a933cdfa0226c28648e577de51d64c081ab85483654
BLAKE2b-256 checksum
How to use checksums
8c7b8fcf6b031428bed923ffa96875369c8054fad477bc18e48f65e78a685785
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.10

Security for vkinfo 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.2 This release

1 release file No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page