-
Notifications
You must be signed in to change notification settings - Fork 94
Optimize queries for participants_data view #533
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
52c3e4c
Small performance changes
reivvax 0b4db39
Add select_related()
reivvax a640764
Add some management tools
reivvax 9e5a7f8
Remove timing utils
reivvax 222a454
removing unused code
twalen 2d1e30f
remove unused scripts
twalen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
106 changes: 106 additions & 0 deletions
106
oioioi/participants/management/commands/import_participants_for_oi.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| import os | ||
| import urllib.request | ||
| import random | ||
|
|
||
| from datetime import date, timedelta | ||
|
|
||
| from django.contrib.auth.models import User | ||
| from django.core.management.base import BaseCommand, CommandError | ||
| from django.db import DatabaseError, transaction | ||
| from django.utils.translation import gettext as _ | ||
|
|
||
| from oioioi.contests.models import Contest | ||
| from oioioi.participants.admin import ParticipantAdmin | ||
| from oioioi.participants.models import Participant | ||
| from oioioi.oi.models import OIRegistration, School, T_SHIRT_SIZES, CLASS_TYPES | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| help = _( | ||
| "Imports users and adds them as participants to <contest_id>.\n" | ||
| "The users do not need to be in the database, they will be inserted dynamically.\n" | ||
| "There should exist some School objects in database. If not, you can generate them with import_schools.py\n" | ||
| "Each line must have: username first_name last_name (space or comma separated).\n" | ||
| "Lines starting with '#' are ignored." | ||
| ) | ||
|
|
||
| def add_arguments(self, parser): | ||
| parser.add_argument('contest_id', type=str, help='Contest to import to') | ||
| parser.add_argument('filename_or_url', type=str, help='Source file') | ||
|
|
||
| def handle(self, *args, **options): | ||
| try: | ||
| contest = Contest.objects.get(id=options['contest_id']) | ||
| except Contest.DoesNotExist: | ||
| raise CommandError(_("Contest %s does not exist") % options['contest_id']) | ||
|
|
||
| # rcontroller = contest.controller.registration_controller() | ||
twalen marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| # if not issubclass( | ||
| # getattr(rcontroller, 'participant_admin', type(None)), ParticipantAdmin | ||
| # ): | ||
| # raise CommandError(_("Wrong type of contest")) | ||
|
|
||
| arg = options['filename_or_url'] | ||
| if arg.startswith('http://') or arg.startswith('https://'): | ||
| self.stdout.write(_("Fetching %s...\n") % (arg,)) | ||
| stream = urllib.request.urlopen(arg) | ||
| stream = (line.decode('utf-8') for line in stream) | ||
| else: | ||
| if not os.path.exists(arg): | ||
| raise CommandError(_("File not found: %s") % arg) | ||
| stream = open(arg, 'r', encoding='utf-8') | ||
|
|
||
| schools = list(School.objects.all()) | ||
| if not schools: | ||
| raise CommandError("No schools found in the database.") | ||
|
|
||
| all_count = 0 | ||
| with transaction.atomic(): | ||
| ok = True | ||
| for line in stream: | ||
| line = line.strip() | ||
| if not line or line.startswith('#'): | ||
| continue | ||
|
|
||
| parts = line.replace(',', ' ').split() | ||
| if len(parts) != 3: | ||
| self.stdout.write(_("Invalid line format: %s\n") % line) | ||
| ok = False | ||
| continue | ||
|
|
||
| username, first_name, last_name = parts | ||
|
|
||
| try: | ||
| user, created = User.objects.get_or_create(username=username) | ||
| if created: | ||
| user.first_name = first_name | ||
| user.last_name = last_name | ||
| user.set_unusable_password() | ||
| user.save() | ||
|
|
||
| Participant.objects.get_or_create(contest=contest, user=user) | ||
| participant, _ = Participant.objects.get_or_create(contest=contest, user=user) | ||
|
|
||
| OIRegistration.objects.create( | ||
| participant=participant, | ||
| address=f"ulica {random.randint(1, 100)}", | ||
| postal_code=f"{random.randint(10, 99)}-{random.randint(100, 999)}", | ||
| city=f"Miasto{random.randint(1, 50)}", | ||
| phone=f"+48 123 456 {random.randint(100, 999)}", | ||
| birthday=date.today() - timedelta(days=random.randint(5000, 8000)), | ||
| birthplace=f"Miejsce{random.randint(1, 100)}", | ||
| t_shirt_size=random.choice(T_SHIRT_SIZES)[0], | ||
| class_type=random.choice(CLASS_TYPES)[0], | ||
| school=random.choice(schools), | ||
| terms_accepted=True, | ||
| ) | ||
| all_count += 1 | ||
| except DatabaseError as e: | ||
| self.stdout.write(_("DB Error for user=%s: %s\n") % (username, str(e))) | ||
| ok = False | ||
|
|
||
| if ok: | ||
| # self.stdout.write(_("Successfully processed %d entries.") % all_count) | ||
| print(f"Successfully processed {all_count} entries.") | ||
| else: | ||
| raise CommandError(_("There were some errors. Database not changed.")) | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import os | ||
| import csv | ||
| import urllib.request | ||
|
|
||
| from django.core.management.base import BaseCommand, CommandError | ||
| from django.db import DatabaseError, transaction | ||
| from django.utils.translation import gettext as _ | ||
|
|
||
| from oioioi.oi.models import School | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| help = _( | ||
| "Inserts School objects into the database from a CSV file or URL. " | ||
| "Expected header: name,address,postal_code,city,province,phone,email\n" | ||
| "Lines starting with '#' are ignored." | ||
| ) | ||
|
|
||
| requires_model_validation = True | ||
|
|
||
| def add_arguments(self, parser): | ||
| parser.add_argument('filename_or_url', type=str, help='CSV file or URL') | ||
|
|
||
| def handle(self, *args, **options): | ||
| arg = options['filename_or_url'] | ||
|
|
||
| if arg.startswith('http://') or arg.startswith('https://'): | ||
| self.stdout.write(_("Fetching %s...\n") % (arg,)) | ||
| stream = urllib.request.urlopen(arg) | ||
| lines = (line.decode('utf-8') for line in stream) | ||
| else: | ||
| if not os.path.exists(arg): | ||
| raise CommandError(_("File not found: %s") % arg) | ||
| with open(arg, 'r', encoding='utf-8') as f: | ||
| lines = f.readlines() | ||
|
|
||
| reader = csv.DictReader( | ||
| (line for line in lines if line.strip() and not line.strip().startswith('#')) | ||
| ) | ||
|
|
||
| with transaction.atomic(): | ||
| all_count = 0 | ||
| inserted_count = 0 | ||
| ok = True | ||
| for row in reader: | ||
| all_count += 1 | ||
| try: | ||
| school, created = School.objects.get_or_create( | ||
| name=row['name'].strip(), | ||
| postal_code=row['postal_code'].strip(), | ||
| defaults={ | ||
| 'address': row['address'].strip(), | ||
| 'city': row['city'].strip(), | ||
| 'province': row['province'].strip(), | ||
| 'phone': row['phone'].strip(), | ||
| 'email': row['email'].strip(), | ||
| 'is_active': True, | ||
| 'is_approved': True, | ||
| } | ||
| ) | ||
| if created: | ||
| inserted_count += 1 | ||
| except DatabaseError as e: | ||
| message = str(e) | ||
| self.stdout.write( | ||
| _("DB Error for school=%(name)s: %(message)s\n") | ||
| % {'name': row.get('name', 'UNKNOWN'), 'message': message} | ||
| ) | ||
| ok = False | ||
| except Exception as e: | ||
| self.stdout.write( | ||
| _("Error for row=%(row)s: %(message)s\n") | ||
| % {'row': row, 'message': str(e)} | ||
| ) | ||
| ok = False | ||
|
|
||
| if ok: | ||
| self.stdout.write(_("Inserted %d new schools (of %d total)") % (inserted_count, all_count)) | ||
| else: | ||
| raise CommandError(_("There were some errors. Database not changed.\n")) |
29 changes: 29 additions & 0 deletions
29
oioioi/participants/management/commands/remove_participants.py
twalen marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| from django.core.management.base import BaseCommand, CommandError | ||
| from oioioi.contests.models import Contest | ||
| from oioioi.participants.models import Participant | ||
| from django.utils.translation import gettext as _ | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| help = _("Removes all participants for the specified contest.") | ||
|
|
||
| def add_arguments(self, parser): | ||
| parser.add_argument('contest_id', type=str, help='Contest ID to clear participants from') | ||
|
|
||
| def handle(self, *args, **options): | ||
| contest_id = options['contest_id'] | ||
|
|
||
| try: | ||
| contest = Contest.objects.get(id=contest_id) | ||
| except Contest.DoesNotExist: | ||
| raise CommandError(_("Contest with ID %s does not exist.") % contest_id) | ||
|
|
||
| participants = Participant.objects.filter(contest=contest) | ||
| count = participants.count() | ||
|
|
||
| if count == 0: | ||
| self.stdout.write(_("No participants found for contest ID %s.") % contest_id) | ||
| return | ||
|
|
||
| participants.delete() | ||
| self.stdout.write(_("Deleted %d participant(s) from contest ID %s.") % (count, contest_id)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.