UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 32 - Code Generator

LEARN

Course Content

Today

Design Patterns

Reusable Design Patterns

Book Data Relationships

If you have more that four data models draw a simple diagram

Use https://www.gliffy.com/

Superhero Data Relationships

Use https://www.gliffy.com/

Problem

Code Cloner Design Pattern

Code Cloner - Why

Code Cloner - When

Code Cloner - How

Code Cloner - What

Version Control

Create a Django Command

coder/management/commands/cloner.py

```python from django.core.management.base import BaseCommand

class Command(BaseCommand):

def handle(self, *args, **options):
    print("CODE CLONER")
    generate_code()

```

Invoke the cloner

bash $ python manage.py cloner

Create the Data Model

book/models.py

python class Note(models.Model): chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, editable=False) author = models.ForeignKey(Author, on_delete=models.CASCADE, editable=False) title = models.CharField(max_length=200) text = models.TextField()

Select the code to leverage

book/urls_book.py book/views_book.py book/tests_book.py templates/book_add.html templates/book_delete.html templates/book_detail.html templates/book_edit.html templates/book_list.html

Choose the files

book/urls_book.py --> book/urls_note.py book/views_book.py --> book/views_note.py book/tests_book.py --> book/tests_note.py templates/book_add.html --> templates/note_add.html templates/book_delete.html --> templates/note_delete.html templates/book_detail.html --> templates/note_detail.html templates/book_edit.html --> templates/note_edit.html templates/book_list.html --> templates/note_list.html

Convert the files

python def convert_file(f1, f2, object1, object2, class1, class2): text = open(f1).read() text = text.replace(object1, object2) text = text.replace(class1, class2) open(f2, 'w').write(text) print(f'{f1} --> {f2}')

Convert all files

python def clone_code(class_name, object_name, old_class, old_object): print(f'\n\nGenerating code \nClass: {class_name}, Object: {object_name}\n') copyfile(f'{old_object}/urls.py', f'{old_object}/urls_{old_object}.py') for f in file_list(old_object).split('\n'): new_file = f.replace(old_object, object_name).replace(f'{object_name}/', f'{old_object}/') convert_file(f, new_file, old_object, object_name, old_class, class_name)

Perform Clone Operation

python def generate_code(): class_name = "Note" object_name = "note" old_class = 'Book' old_object = 'book' clone_code(class_name, object_name, old_class, old_object)

Integrate in structure

Test and fix

BUILD

Demo Code

Final Project