The basic guide for EventVerify app server configuration.
The basic guide for EventVerify app server configuration.
Setting up server with Django
This guide provides step-by-step instructions to set up a Django-based server for serving ticket data securely, using different authentication methods and formats. Choosing the right method depends on your project's requirements. Here's an overview to help you decide:
- **CSV**: Ideal for projects where data is exported for offline analysis or integration with external systems (e.g., spreadsheets or accounting software).
- **JSON**: Best suited for real-time applications or APIs that integrate with modern web or mobile apps. JSON is lightweight, structured, and easily parsed by applications.
1. **Bearer Token Authentication**
- **Pros**: Simple, effective for stateless APIs, and widely used in RESTful services.
- **Use Case**: Suitable for machine-to-machine communication or scenarios where the client can securely store the token (e.g., server-side applications).
- **Setup Chapter**: CSV with Bearer Token Authentication or JSON with Bearer Token Authentication.
2. **Username and Password Authentication**
- **Pros**: More familiar to users and allows human-readable credentials. Easy to integrate into existing user authentication systems.
- **Use Case**: Ideal for applications requiring user authentication, such as admin dashboards or tools managed by multiple team members.
- **Setup Chapter**: CSV with Username and Password Authentication or JSON with Username and Password Authentication.
- **CSV with Bearer Token Authentication**: Use for exporting secure, token-protected CSV files for system integrations or reporting tools.
- **CSV with Username and Password Authentication**: Ideal for admin tools where users log in with credentials to download CSV data.
- **JSON with Bearer Token Authentication**: Use for building stateless, token-secured APIs that serve structured ticket data to applications.
- **JSON with Username and Password Authentication**: Best for scenarios requiring authenticated access to structured data, often used in admin or reporting applications.
This guide provides standalone chapters for each setup, so you can jump directly to the section that matches your needs.
CSV vs. JSON
Authentication Methods
When to Use?
Guide to Setting Up a CSV File Server with Auth Token
Guide to Setting Up a CSV File Server with Username and Password Authentication
Guide to Setting Up a JSON Server with Bearer Token Authentication
Guide to Setting Up a JSON Server with Username and Password Authentication
Configure URLs
Test the Setup
Guide to Setting Up a CSV File Server with Auth Token
Before starting, ensure you have the following:
1. Python 3.x installed on your system.
2. A fresh Django project. If you don't have one, run:
django-admin startproject ticket_server
cd ticket_server
python manage.py startapp tickets
3. Add the `tickets` app to your Django project:
- Open `settings.py` in the `ticket_server` folder.
- Add `'tickets'` to the `INSTALLED_APPS` list.
4. Install required libraries:
pip install django phonenumbers
1. Navigate to the `tickets` app folder and open `models.py`.
2. Add the following code to define the `GlobalConfig` and `Ticket` models:
from django.db import models
import uuid
class GlobalConfig(models.Model):
name = models.CharField(max_length=120, default="default")
auth_code = models.CharField(
max_length=120,
default="3fK8#Tg7lQp45aFz!nXw9YrMv2Dc%hJ0VrL6oK7aBnC5jXqRmSaW8tYpL3sN1vB"
)
def __str__(self):
return f"{self.name}"
def generate_ticket_id():
return str(uuid.uuid4())
class Ticket(models.Model):
new_idd = models.UUIDField(primary_key=True, default=generate_ticket_id, editable=False)
ticket_id = models.CharField(max_length=255)
times_scanned = models.IntegerField(default=0)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.ticket_id
3. Run migrations to create the database tables:
python manage.py makemigrations
python manage.py migrate
1. Open `views.py` in the `tickets` app folder and add the following imports and helper functions:
from django.http import HttpResponse
from .models import Ticket, GlobalConfig
# Helper function to get the first alphabetical GlobalConfig
def get_global_config():
return GlobalConfig.objects.order_by('name').first()
# Verify Bearer Token Authentication
def verify_bearer_token(request):
config = get_global_config()
auth_header = request.headers.get('Authorization', '')
token_type, _, token = auth_header.partition(' ')
return token_type == 'Bearer' and token == config.auth_code
2. Add the CSV generation and token-protected view:
import csv
from django.views.decorators.http import require_http_methods
def show_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="tickets.csv"'
writer = csv.writer(response)
writer.writerow(['Ticket ID', 'Scanned', 'Description'])
for ticket in Ticket.objects.all():
writer.writerow([ticket.ticket_id, ticket.times_scanned, ticket.description])
return response
@require_http_methods(["GET"])
def bearer_csv(request):
if not verify_bearer_token(request):
return HttpResponse("Unauthorized", status=401)
return show_csv(request)
1. Create a `urls.py` file in the `tickets` app folder (if it doesn’t exist) and add the following code:
from django.urls import path
from .views import bearer_csv
urlpatterns = [
path('csv/', bearer_csv, name='bearer_csv'),
]
2. Link the app’s `urls.py` to the main project:
Open the `urls.py` file in the `ticket_server` folder.
from django.urls import include, path
urlpatterns = [
path('tickets/', include('tickets.urls')),
]
1. Run the server:
python manage.py runserver
2. Create a `GlobalConfig` entry in the Django admin panel:
- Run:
python manage.py createsuperuser
- Log in at `http://127.0.0.1:8000/admin/`.
- Add a new `GlobalConfig` object with your desired `auth_code`.
3. Add some tickets to test the functionality:
- Either through the admin panel or directly in the shell:
python manage.py shell
from tickets.models import Ticket
Ticket.objects.create(ticket_id="123456", description="Test ticket”)
4. Test the token-protected endpoint:
- Use `curl` or a tool like Postman to make a request:
curl -H "Authorization: Bearer <your_auth_code>" http://127.0.0.1:8000/tickets/csv/
Guide to Setting Up a CSV File Server with Username and Password Authentication
Before starting, ensure you have the following:
1. Python 3.x installed on your system.
2. A fresh Django project. If you don't have one, run:
django-admin startproject ticket_server
cd ticket_server
python manage.py startapp tickets
3. Add the `tickets` app to your Django project:
- Open `settings.py` in the `ticket_server` folder.
- Add `'tickets'` to the `INSTALLED_APPS` list.
4. Install required libraries:
pip install django phonenumbers
1. Navigate to the `tickets` app folder and open `models.py`.
2. Add the following code to define the `GlobalConfig` and `Ticket` models:
from django.db import models
import uuid
class GlobalConfig(models.Model):
name = models.CharField(max_length=120, default="default")
username = models.CharField(max_length=120, default="example_user")
password = models.CharField(max_length=120, default="example_password")
def __str__(self):
return f"{self.name}"
def generate_ticket_id():
return str(uuid.uuid4())
class Ticket(models.Model):
new_idd = models.UUIDField(primary_key=True, default=generate_ticket_id, editable=False)
ticket_id = models.CharField(max_length=255)
times_scanned = models.IntegerField(default=0)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.ticket_id
3. Apply the migrations:
python manage.py makemigrations
python manage.py migrate
1. Open `views.py` in the `tickets` app folder and add the following imports and helper functions:
import base64
from django.http import HttpResponse
from .models import Ticket, GlobalConfig
# Helper function to get the first alphabetical GlobalConfig
def get_global_config():
return GlobalConfig.objects.order_by('name').first()
# Verify Basic Authentication
def verify_basic_auth(request):
config = get_global_config()
auth_header = request.headers.get('Authorization', '')
token_type, _, encoded_credentials = auth_header.partition(' ')
if token_type != 'Basic' or not encoded_credentials:
return False
decoded_credentials = base64.b64decode(encoded_credentials).decode()
username, _, password = decoded_credentials.partition(':')
return username == config.username and password == config.password
1. Add a function to generate and serve the CSV file:
import csv
from django.views.decorators.http import require_http_methods
def show_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="tickets.csv"'
writer = csv.writer(response)
writer.writerow(['Ticket ID', 'Scanned', 'Description'])
for ticket in Ticket.objects.all():
writer.writerow([ticket.ticket_id, ticket.times_scanned, ticket.description])
return response
2. Add the Basic Authentication-protected view:
@require_http_methods(["GET"])
def basic_csv(request):
if not verify_basic_auth(request):
return HttpResponse("Unauthorized", status=401)
return show_csv(request)
1. Create a `urls.py` file in the `tickets` app folder (if it doesn’t exist) and add the following code:
from django.urls import path
from .views import basic_csv
urlpatterns = [
path('csv/basic/', basic_csv, name='basic_csv'),
]
2. Link the app’s `urls.py` to the main project:
Open the `urls.py` file in the `ticket_server` folder.
from django.urls import include, path
urlpatterns = [
path('tickets/', include('tickets.urls')),
]
python manage.py runserver
python manage.py createsuperuser
- Log in at `http://127.0.0.1:8000/admin/`.
- Add a new `GlobalConfig` object with the desired username and password:
- `username`: `test_user`
- `password`: `test_password`
3. Add some test tickets:
python manage.py shell
from tickets.models import Ticket
Ticket.objects.create(ticket_id="123456", description="Test ticket”)
4. Test the Basic Authentication-protected endpoint:
curl -u test_user:test_password http://127.0.0.1:8000/tickets/csv/basic/
Guide to Setting Up a JSON Server with Bearer Token Authentication
Before starting, ensure you have the following:
1. Python 3.x installed on your system.
2. A fresh Django project. If you don't have one, run:
django-admin startproject ticket_server
cd ticket_server
python manage.py startapp tickets
3. Add the `tickets` app to your Django project:
- Open `settings.py` in the `ticket_server` folder.
- Add `'tickets'` to the `INSTALLED_APPS` list.
4. Install required libraries:
pip install django phonenumbers
1. Navigate to the `tickets` app folder and open `models.py`.
2. Add the following code to define the `GlobalConfig` and `Ticket` models:
from django.db import models
import uuid
class GlobalConfig(models.Model):
name = models.CharField(max_length=120, default="default")
auth_code = models.CharField(max_length=120, default="example_token")
def __str__(self):
return f"{self.name}"
def generate_ticket_id():
return str(uuid.uuid4())
class Ticket(models.Model):
new_idd = models.UUIDField(primary_key=True, default=generate_ticket_id, editable=False)
ticket_id = models.CharField(max_length=255)
times_scanned = models.IntegerField(default=0)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.ticket_id
3. Apply the migrations:
python manage.py makemigrations
python manage.py migrate
1. Open `views.py` in the `tickets` app folder and add the following imports and helper functions:
from django.http import JsonResponse
from .models import Ticket, GlobalConfig
# Helper function to get the first alphabetical GlobalConfig
def get_global_config():
return GlobalConfig.objects.order_by('name').first()
# Verify Bearer Token Authentication
def verify_bearer_token(request):
config = get_global_config()
auth_header = request.headers.get('Authorization', '')
token_type, _, token = auth_header.partition(' ')
return token_type == 'Bearer' and token == config.auth_code
1. Add a view to generate and serve JSON data:
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET"])
def bearer_json(request):
if not verify_bearer_token(request):
return HttpResponse("Unauthorized", status=401)
tickets = Ticket.objects.values('ticket_id', 'times_scanned', 'description')
return JsonResponse(list(tickets), safe=False)
1. Create a `urls.py` file in the `tickets` app folder (if it doesn’t exist) and add the following code:
from django.urls import path
from .views import bearer_json
urlpatterns = [
path('json/bearer/', bearer_json, name='bearer_json'),
]
2. Link the app’s `urls.py` to the main project:
Open the `urls.py` file in the `ticket_server` folder.
from django.urls import include, path
urlpatterns = [
path('tickets/', include('tickets.urls')),
]
python manage.py runserver
python manage.py createsuperuser
python manage.py shell
from tickets.models import Ticket
Ticket.objects.create(ticket_id="123456", description="Test ticket”)
curl -H "Authorization: Bearer example_token" http://127.0.0.1:8000/tickets/json/bearer/
Guide to Setting Up a JSON Server with Username and Password Authentication
Before starting, ensure you have the following:
1. Python 3.x installed on your system.
2. A fresh Django project. If you don't have one, run:
django-admin startproject ticket_server
cd ticket_server
python manage.py startapp tickets
3. Add the `tickets` app to your Django project:
- Open `settings.py` in the `ticket_server` folder.
- Add `'tickets'` to the `INSTALLED_APPS` list.
4. Install required libraries:
pip install django phonenumbers
1. Navigate to the `tickets` app folder and open `models.py`.
2. Add the following code to define the `GlobalConfig` and `Ticket` models:
from django.db import models
import uuid
class GlobalConfig(models.Model):
name = models.CharField(max_length=120, default="default")
auth_code = models.CharField(max_length=120, default="example_token")
def __str__(self):
return f"{self.name}"
def generate_ticket_id():
return str(uuid.uuid4())
class Ticket(models.Model):
new_idd = models.UUIDField(primary_key=True, default=generate_ticket_id, editable=False)
ticket_id = models.CharField(max_length=255)
times_scanned = models.IntegerField(default=0)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.ticket_id
3. Apply the migrations:
python manage.py makemigrations
python manage.py migrate
1. Open `views.py` in the `tickets` app folder and add the following imports and helper functions:
import base64
from django.http import JsonResponse
from .models import Ticket, GlobalConfig
# Helper function to get the first alphabetical GlobalConfig
def get_global_config():
return GlobalConfig.objects.order_by('name').first()
# Verify Basic Authentication
def verify_basic_auth(request):
config = get_global_config()
auth_header = request.headers.get('Authorization', '')
token_type, _, encoded_credentials = auth_header.partition(' ')
if token_type != 'Basic' or not encoded_credentials:
return False
decoded_credentials = base64.b64decode(encoded_credentials).decode()
username, _, password = decoded_credentials.partition(':')
return username == config.username and password == config.password
1. Add a view to generate and serve JSON data:
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET"])
def basic_json(request):
if not verify_basic_auth(request):
return HttpResponse("Unauthorized", status=401)
tickets = Ticket.objects.values('ticket_id', 'times_scanned', 'description')
return JsonResponse(list(tickets), safe=False)
1. Create a `urls.py` file in the `tickets` app folder (if it doesn’t exist) and add the following code:
from django.urls import path
from .views import basic_json
urlpatterns = [
path('json/basic/', basic_json, name='basic_json'),
]
2. Link the app’s `urls.py` to the main project:
Open the `urls.py` file in the `ticket_server` folder.
from django.urls import include, path
urlpatterns = [
path('tickets/', include('tickets.urls')),
]
python manage.py runserver
python manage.py createsuperuser
python manage.py shell
from tickets.models import Ticket
Ticket.objects.create(ticket_id="123456", description="Test ticket”)
curl -u test_user:test_password http://127.0.0.1:8000/tickets/json/basic/
You have successfully set up a JSON server protected by Basic Authentication. Users must provide valid credentials in the request header to access the data.
Duszekjk Jacek Kałużny
Cookies
This website uses cookies because it is a website