Skip to content

Commit

Permalink
Merge pull request #14 from githubuniverseworkshops/arilivigni/self-s…
Browse files Browse the repository at this point in the history
…ervice-prompting

Arilivigni/self service prompting
  • Loading branch information
bryantson authored Oct 25, 2024
2 parents 38df12d + a5681c8 commit 3ced6b5
Show file tree
Hide file tree
Showing 12 changed files with 137 additions and 43 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ This workshop involves several technology stacks, therefore it is essential that
### Objectives

**Walk through a real-world use case**:
- Building a fitness tracker app from end to end
- Create a full stack of technologies for the infrastructure, frontend, and backend
- Using the latest **GitHub Copilot** features

- Building a fitness tracker app from end to end
- Create a full stack of technologies for the infrastructure, frontend, and backend
- Using the latest **GitHub Copilot** features

### Key takeaways

Expand Down
2 changes: 1 addition & 1 deletion docs/1_Story/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ In this workshop, you'll:
- User authentication and profiles
- Activity logging and tracking
- Team creation and management
- Competitive leaderboards
- A competitive leaderboard
- Personalized workout suggestions

### GitHub Copilot and Copilot Chat
Expand Down
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed docs/3_GettingStarted/3_2_StepByStep.png
Binary file not shown.
Binary file modified docs/3_GettingStarted/3_3_OctoFitTrackerDirTree.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
35 changes: 31 additions & 4 deletions docs/3_GettingStarted/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ generate instructions in this order
4. The Django project octofit-tracker directory will have all the backend components for the app
5. Create the django app directly in the directory octofit_tracker/backend
6. Setup the octofit-tracker/frontend directory will store the react app with no subdirectories
7. Install bootstrap and import it
8. Install mongodb via 'apt-get' and setup mongodb with the 'sudo service mongodb start' and 'sudo service mongodb status'
7. install react framework
8. Install bootstrap and import it
9. Commands to install mongodb via 'apt-get'
10. Commands start mongodb with the 'sudo service mongodb start' and 'sudo service mongodb status'
Tha directory tree for the OctoFit Tracker App
Expand Down Expand Up @@ -69,10 +71,35 @@ Let's think about this step by step
Important to avoid using public code and we do NOT need to initialize the git repository
```

![create project plan](./3_1_AskCopilotProjectCreation.png)</br>
![create project plan](./3_1_GettingStartedPromptProjectCreation.png)</br>

![step by step](./3_2_StepByStep.png)</br>
![step by step](./3_2_GettingStartedStepByStep.png)</br>

![octofit-tracker app directory tree](./3_3_OctoFitTrackerDirTree.png)</br>

### Cheat sheet of commands to use to create the OctoFit Tracker structure

```bash
mkdir -p octofit-tracker/{backend,frontend}

python3 -m venv octofit-tracker/backend/venv
source octofit-tracker/backend/venv/bin/activate
pip install -r octofit-tracker/requirements.txt

django-admin startproject octofit_tracker octofit-tracker/backend

npx create-react-app octofit-tracker/frontend

cd ../frontend
npm install bootstrap

echo "import 'bootstrap/dist/css/bootstrap.min.css';" >> src/index.js

sudo apt-get update
sudo apt-get install -y mongodb

sudo service mongodb start
sudo service mongodb status
```

[:arrow_backward: Previous: Prerequisites and development environment setup](../2_Prerequisites/README.md) | [Next: Let's work on front end stuff :arrow_forward:](../4_FrontEndWork/README.md)
2 changes: 1 addition & 1 deletion docs/4_FrontEndWork/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ function App() {
<ul>
<li><a href="/">Home</a></li>
<li><a href="/profile">Profile</a></li>
<li><a href="/activities">Activities</a></li>
<li><a href="/activity">Activity</a></li>
<li><a href="/teams">Teams</a></li>
<li><a href="/leaderboard">Leaderboard</a></li>
<li><a href="/workouts">Workouts</a></li>
Expand Down
75 changes: 57 additions & 18 deletions docs/5_BackendSettings/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,19 @@ Type the following prompt in GitHub Copilot Chat:
```text
In our next steps lets think step by step and setup the following in this order
1. Initialize the mongo octofit_db database and create a correct table structure for users, teams, activities, leaderboards, and workouts collections
1. Initialize the mongo octofit_db database and create a correct table structure for users, teams, activity, leaderboard, and workouts collections
2. Make sure there is a unique id for primary key for the user collection
ex. db.users.createIndex({ "email": 1 }, { unique: true })
3. settings.py in our django project for mongodb octofit_db database including localhost and the port
4. settings.py in our django project setup for all installed apps. ex djongo, octofit_tracker, rest_framework
5. In octofit_tracker project setup and use command touch models.py, serializers.py, urls.py, and views.py for users, teams, activities, leaderboards, and workouts
6. make sure urls.py has a root, admin, and api endpoints
5. In octofit_tracker project setup and use command touch models.py, serializers.py, urls.py, and views.py for users, teams, activity, leaderboard, and workouts
6. Generate code for models.py, serializers.py, and views.py and
7. make sure urls.py has a root, admin, and api endpoints
urlpatterns = [
path('', api_root, name='api-root'), # Root endpoint
path('admin/', admin.site.urls), # Admin endpoint
path('api/', include(router.urls)), # API endpoint
]
```

![OctoFit Tracker backend prompt](./5_1_BackendSettingsPrompt.png)</br>
Expand All @@ -22,6 +28,24 @@ In our next steps lets think step by step and setup the following in this order
![OctoFit Tracker backend response step 3 continued](./5_2_BackendSettingsStep3_2.png)</br>
![OctoFit Tracker backend response step 3 continued](./5_2_BackendSettingsStep3_3.png)</br>

### MongoDB commands to setup `octofit_db`

```bash
mongo
use octofit_db
db.createCollection("users")
db.createCollection("teams")
db.createCollection("activity")
db.createCollection("leaderboard")
db.createCollection("workouts")
db.users.createIndex({ "email": 1 }, { unique: true })
db.teams.createIndex({ "name": 1 }, { unique: true })
db.activity.createIndex({ "activity_id": 1 }, { unique: true })
db.leaderboard.createIndex({ "leaderboard_id": 1 }, { unique: true })
db.workouts.createIndex({ "workout_id": 1 }, { unique: true })
exit
```
### Sample settings.py
```json
Expand Down Expand Up @@ -127,11 +151,24 @@ class WorkoutSerializer(serializers.ModelSerializer):
#### views.py
```python
# FILE: octofit_tracker/views.py
# FILE: octofit-tracker/backend/octofit_tracker/views.py

from .serializers import UserSerializer, TeamSerializer, ActivitySerializer, LeaderboardSerializer, WorkoutSerializer
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from .serializers import UserSerializer, TeamSerializer, ActivitySerializer, LeaderboardSerializer, WorkoutSerializer
from .models import User, Team, Activity, Leaderboard, Workout

@api_view(['GET'])
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'teams': reverse('team-list', request=request, format=format),
'activity': reverse('activity-list', request=request, format=format),
'leaderboard': reverse('leaderboard-list', request=request, format=format),
'workouts': reverse('workout-list', request=request, format=format),
})

class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
Expand All @@ -152,23 +189,12 @@ class LeaderboardViewSet(viewsets.ModelViewSet):
class WorkoutViewSet(viewsets.ModelViewSet):
queryset = Workout.objects.all()
serializer_class = WorkoutSerializer

@api_view(['GET'])
def api_root(request, format=None):
base_url = 'http://upgraded-space-happiness-959pr7vpgw3p7vv-8000.app.github.dev/'
return Response({
'users': base_url + 'api/users/?format=api',
'teams': base_url + 'api/teams/?format=api',
'activities': base_url + 'api/activities/?format=api',
'leaderboards': base_url + 'api/leaderboards/?format=api',
'workouts': base_url + 'api/workouts/?format=api'
})
```
#### urls.py
```python
# FILE: octofit_tracker/urls.py
# FILE: octofit-tracker/backend/octofit_tracker/urls.py

from django.contrib import admin
from django.urls import path, include
Expand All @@ -189,4 +215,17 @@ urlpatterns = [
]
```
## GitHub Copilot Chat commands to help debug issues
```text
/help

#selection - The current selection in the active editor
#codebase - Searches through the codebase and pulls out relevant information for the query.
#editor - The visible source code in the active editor
#terminalLastCommand - The active terminal's last run command
#terminalSelection - The active terminal's selection
#file - Choose a file in the workspace
```
[:arrow_backward: Previous: Let's work on front end](../4_FrontEndWork/README.md) | [Next: Populate the database with sample data :arrow_forward:](../6_PopulateDBwData/README.md)
49 changes: 38 additions & 11 deletions docs/6_PopulateDBwData/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ Type the following prompt in GitHub Copilot Chat:
```text
Let's use manage.py to get the database setup and populated based on fields in models.py
- Create populate_db.py so it initializes and deletes previous data and recreates it
- populate_db.py creates users, teams, activities, leaderboards, and workouts
- Create populate_db.py as a manage.py command so it initializes and deletes previous data and recreates it
- populate_db.py creates users, teams, activity, leaderboard, and workouts
- users will be super hero users
- Include steps to migrate in the octofit_tracker project
```
Expand All @@ -31,21 +31,28 @@ Let's use manage.py to get the database setup and populated based on fields in m
![create the populate_db.py step 1_1](./6_2_PopulateDBwDataStep1_1.png)
![create the populate_db.py step 1_2](./6_2_PopulateDBwDataStep1_2.png)

### Commands to create the directory structure for populate_db.py

```bash
mkdir -p octofit-tracker/backend/octofit_tracker/management/commands
touch octofit-tracker/backend/octofit_tracker/management/__init__.py
touch octofit-tracker/backend/octofit_tracker/management/commands/__init__.py
touch octofit-tracker/backend/octofit_tracker/management/commands/populate_db.py
```

### Sample code for populate_db.py

```python
# FILE: octofit-tracker/backend/octofit_tracker/management/commands/populate_db.py

# octofit_tracker/management/commands/populate_db.py

from django.core.management.base import BaseCommand
from octofit_tracker.models import User, Team, Activity, Leaderboard, Workout
from django.conf import settings
from pymongo import MongoClient
from datetime import timedelta

class Command(BaseCommand):
help = 'Populate the database with superhero users, teams, activities, leaderboards, and workouts'
help = 'Populate the database with superhero users, teams, activity, leaderboard, and workouts'

def handle(self, *args, **kwargs):
# Connect to MongoDB
Expand All @@ -55,8 +62,8 @@ class Command(BaseCommand):
# Drop existing collections
db.users.drop()
db.teams.drop()
db.activities.drop()
db.leaderboards.drop()
db.activity.drop()
db.leaderboard.drop()
db.workouts.drop()

# Populate users
Expand Down Expand Up @@ -95,7 +102,7 @@ class Command(BaseCommand):
else:
self.stdout.write(self.style.WARNING(f'Team {team.name} already exists'))

# Populate activities
# Populate activity
activities = [
{'user': user_objects[0], 'activity_type': 'Flying', 'duration': timedelta(hours=1)},
{'user': user_objects[1], 'activity_type': 'Martial Arts', 'duration': timedelta(hours=2)},
Expand All @@ -111,7 +118,7 @@ class Command(BaseCommand):
else:
self.stdout.write(self.style.WARNING(f'Activity for {activity.user.username} already exists'))

# Populate leaderboards
# Populate leaderboard
leaderboards = [
{'user': user_objects[0], 'score': 100},
{'user': user_objects[1], 'score': 90},
Expand All @@ -133,7 +140,7 @@ class Command(BaseCommand):
{'name': 'Martial Arts Training', 'description': 'Training for martial arts'},
{'name': 'Amazonian Training', 'description': 'Training for Amazonian warriors'},
{'name': 'Speed Training', 'description': 'Training for super speed'},
{'name': 'Aquatic Training', 'description': 'Training for underwater activities'},
{'name': 'Aquatic Training', 'description': 'Training for underwater activity'},
]

for workout_data in workouts:
Expand All @@ -144,6 +151,26 @@ class Command(BaseCommand):
self.stdout.write(self.style.WARNING(f'Workout {workout.name} already exists'))
```

![Migrate and populate db](./5_3_MigratePopulateDb.png)
### Run the following commands to migrate the database and populate it with data

```bash
cd octofit-tracker/backend
python manage.py makemigrations
python manage.py migrate
python manage.py populate_db
```

## GitHub Copilot Chat commands to help debug issues

```text
/help
#selection - The current selection in the active editor
#codebase - Searches through the codebase and pulls out relevant information for the query.
#editor - The visible source code in the active editor
#terminalLastCommand - The active terminal's last run command
#terminalSelection - The active terminal's selection
#file - Choose a file in the workspace
```

[:arrow_backward: Previous: The OctoFit Tracker database and app backend creation](../5_BackendSettings/README.md) | [Next: Using the Codespace endpoint to access the Django REST Framework :arrow_forward:](../7_CodespaceDjangoRESTFramework/README.md)
10 changes: 5 additions & 5 deletions docs/7_CodespaceDjangoRESTFramework/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Type the following prompt in GitHub Copilot Chat:
```text
Let's do the following step by step
- update #file:views.py to replace the return for the rest api url endpiints with the codespace url http://upgraded-space-happiness-959pr7vpgw3p7vv.github.dev/-8000.app.github.dev for django
- update #file:views.py to replace the return for the rest api url endpiints with the codespace url http://[REPLACE-THIS-WITH-YOUR-CODESPACE-NAME]-8000.app.github.dev for django
- Replace <codespace-name> with [REPLACE-THIS-WITH-YOUR-CODESPACE-NAME]
- Run the Django server
Expand All @@ -19,8 +19,8 @@ Vary: Accept
{
"users": "http://localhost:8000/api/users/?format=api",
"teams": "http://localhost:8000/api/teams/?format=api",
"activities": "http://localhost:8000/api/activities/?format=api",
"leaderboards": "http://localhost:8000/api/leaderboards/?format=api",
"activity": "http://localhost:8000/api/activity/?format=api",
"leaderboard": "http://localhost:8000/api/leaderboard/?format=api",
"workouts": "http://localhost:8000/api/workouts/?format=api"
}
Expand All @@ -31,8 +31,8 @@ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accep
{
"users": "http://<codespace-name>-8000.app.github.dev/users/api/users/?format=api",
"teams": "http://<codespace-name>-8000.app.github.dev/api/teams/?format=api",
"activities": "http://<codespace-name>-8000.app.github.dev/api/activities/?format=api",
"leaderboards": "http://<codespace-name>-8000.app.github.dev/api/leaderboards/?format=api",
"activity": "http://<codespace-name>-8000.app.github.dev/api/activity/?format=api",
"leaderboard": "http://<codespace-name>-8000.app.github.dev/api/leaderboard/?format=api",
"workouts": "http://<codespace-name>-8000.app.github.dev/api/workouts/?format=api"
}
```
Expand Down

0 comments on commit 3ced6b5

Please sign in to comment.