-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
populate_communities.py
81 lines (61 loc) · 2.21 KB
/
populate_communities.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""
To populate telegram links into out `community` service.
How to use:
run in the terminal:
`python populate_communities.py {dev|prod}`
"""
import os
import sys
import csv
import requests as rq
from requests.exceptions import RequestException
from bs4 import BeautifulSoup
settings_type = sys.argv[1]
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE", "petroly.settings." + settings_type
)
# the above line is sufficient
# settings.configure()
print('DJANGO_SETTINGS_MODULE: ', os.environ.get("DJANGO_SETTINGS_MODULE"))
with open('data/telegram_links.txt') as file:
urls = file.readlines()
def find_and_populate():
for url in urls:
url = url.removesuffix('\n')
print(f'Working on {url}')
try:
res = rq.get(url)
except RequestException as exc:
print(f"error while requesting {url} : {exc}")
continue
soup = BeautifulSoup(res.content, 'html.parser')
title = soup.find('div', class_='tgme_page_title').span.contents[0]
img_url = soup.find('img', class_='tgme_page_photo_image')
description = soup.find('div', class_='tgme_page_description')
try:
obj = Community.objects.get(link=url)
print('Community is already exist with the same link. ', obj)
except Community.DoesNotExist:
if img_url:
img = upload_image(
img_url['src'],
format="jpg",
overwrite=True,
invalidate=True,
transformation=[{"width": 200, "height": 200, "crop": "fill"}],
folder=f"communities/{settings_type}/icons",
)
Community.objects.create(
link=url,
name=title,
icon=img if img_url else None,
category=Community.CategoryEnum.EDU,
platform=Community.PlatformEnum.TELEGRAM,
description=description.contents[0] if description else "",
)
if __name__ == '__main__':
import django
django.setup()
from cloudinary.uploader import upload_image
from communities.models import Community
find_and_populate()