程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python版醫院掛號系統,基於Django+MySQL+Redis,支持支付寶掃碼付款

編輯:Python

ython版醫院掛號系統,基於Django+MySQL+Redis,支持支付寶掃碼付款。運行程序前請先申請支付寶API及支付寶公鑰和私鑰,可登錄支付寶開放平台申請。
患者:登錄、注冊、掛號(選擇科室、選擇醫生、選擇時間、填寫病情、支付寶支付)、展示掛號單。
醫生:登錄、展示並處理掛號單。
管理員:增刪查改數據。
程序運行截圖




核心代碼:
views.py

from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.shortcuts import render
from django.shortcuts import render
from django.views import View
from .models import *
import datetime
import uuid
from alipay import AliPay
from django.db.models import Q
# Create your views here.
class ChooseLoginView(View):
'''選擇身份登錄'''
def get(self, request):
return render(request, 'chooselogin.html')
class PatientLoginView(View):
'''患者登錄'''
def get(self, request):
return render(request, 'patientlogin.html')
def post(self, request):
phone = request.POST.get('phone', '')
password = request.POST.get('password', '')
patient_list = Patient.objects.filter(phone=phone, password=password)
if patient_list:
request.session['patient'] = patient_list[0]
return HttpResponseRedirect("/patientcenter/")
return HttpResponse("登錄有問題")
class DoctorLoginView(View):
'''醫生登錄'''
def get(self, request):
return render(request, 'doctorlogin.html')
def post(self, request):
phone = request.POST.get('phone', '')
password = request.POST.get('password', '')
doctor_list = Doctor.objects.filter(phone=phone, password=password)
if doctor_list:
request.session['doctor'] = doctor_list[0]
return HttpResponseRedirect("/doctorcenter/")
return HttpResponse("登錄有問題")
class PatientRegisterView(View):
'''患者注冊'''
def get(self, request):
return render(request, 'patientregister.html')
def post(self, request):
# 只能注冊患者賬號 醫生賬號只能由管理員添加
phone = request.POST.get('phone', '')
patientlist = Patient.objects.filter(phone=phone)
if patientlist:
return render(request, 'patientregister.html', {
"err": 1, "tips": "*該號碼已經被注冊"})
else:
password = request.POST.get('password', '')
name = request.POST.get('name', '')
sex = request.POST.get('sex', '')
age = request.POST.get('age', '')
patient = Patient.objects.create(phone=phone, password=password, name=name, sex=sex, age=age)
if patient:
return HttpResponseRedirect("/patientlogin/")
return HttpResponseRedirect("/patientregister/")
class PatientCenterView(View):
'''患者界面'''
def get(self, request):
patient = request.session.get('patient', '')
return render(request, 'patientcenter.html', {
'patient_name': patient.name})
class ChooseDepartmentView(View):
'''選擇科室'''
def get(self, request):
parentid_department_list = [o.id for o in Department.objects.filter(parentid=0)]
all_department_list = dict()
for id in parentid_department_list:
all_department_list[Department.objects.filter(id=id)[0].name] = Department.objects.filter(parentid=id)
# print(all_department_list)
return render(request, 'choosedepartment.html', {
'all_department_list': all_department_list})
class ChooseDoctorAndTimeView(View):
'''選擇醫生和時間'''
def get(self, request, department_id):
department_id = int(department_id)
department_name = Department.objects.get(id=department_id).name # 科室名字
doctor_list = Doctor.objects.filter(department_id=department_id) # 當前科室裡的醫生
doctor_time_number_list = [] # 此醫生及其的可預約時間和人數列表
for doctor in doctor_list:
doctor_id = doctor.id
doctor_time_number_list.append([doctor, TimeNumber.objects.get(doctor_id=doctor_id)])
tomorrow = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
return render(request, 'choosedoctorandtime.html',
{
'department_name': department_name, 'doctor_time_number_list': doctor_time_number_list,
'department_id': department_id, 'tomorrow': tomorrow})
# 支付寶公鑰
alipay_public_key = """-----BEGIN PUBLIC KEY----- -----END PUBLIC KEY-----"""
# 應用私鑰
my_private_key = """-----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY-----"""
# 創建AliPay對象
alipay = AliPay(
appid='',
app_notify_url='http://127.0.0.1:8000/checkpay/',
app_private_key_string=my_private_key,
alipay_public_key_string=alipay_public_key,
sign_type='RSA2',
debug=True
)
class ConfirmRegistrationView(View):
'''確認掛號信息'''
def get(self, request, department_id, doctor_id, consultation_hours):
department_id = int(department_id)
doctor_id = int(doctor_id)
patient = request.session.get('patient', '')
doctor = Doctor.objects.get(id=doctor_id)
department = Department.objects.get(id=department_id)
patient_name = patient.name
doctor_name = doctor.name
registration_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
consultation_hours = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime(
"%Y-%m-%d") + " " + consultation_hours
# doctor_id
patient_id = patient.id
address = department.address
registration_price = doctor.registration_price
# print(patient_name,doctor_name,registration_time,consultation_hours,doctor_id,patient_id,address)
return render(request, 'confirmregistration.html', {
'patient_name': patient_name, 'doctor_name': doctor_name,
'registration_time': registration_time,
'consultation_hours': consultation_hours,
'doctor_id': doctor_id, 'patient_id': patient_id,
'address': address,
'registration_price': registration_price})
def post(self, request):
patient_name = request.POST.get('patient_name', '')
doctor_name = request.POST.get('doctor_name', '')
registration_time = request.POST.get('registration_time', '')
consultation_hours = request.POST.get('consultation_hours', '')
illness = request.POST.get('illness', '')
doctor_id = request.POST.get('doctor_id', '')
patient_id = request.POST.get('patient_id', '')
address = request.POST.get('address', '')
out_trade_num = uuid.uuid4().hex
payway = 'alipay'
status = '待支付'
isdelete = 1
register = Register.objects.create(patient_name=patient_name, doctor_name=doctor_name,
registration_time=registration_time,
consultation_hours=consultation_hours, illness=illness, doctor_id=doctor_id,
patient_id=patient_id, address=address, isdelete=isdelete,
out_trade_num=out_trade_num,
payway=payway, status=status)
registration_price = request.POST.get('registration_price', '')
params = alipay.api_alipay_trade_page_pay(
subject='醫院掛號',
out_trade_no=register.out_trade_num,
total_amount=registration_price,
return_url='http://127.0.0.1:8000/checkpay/'
)
url = 'https://openapi.alipaydev.com/gateway.do' + '?' + params
return HttpResponseRedirect(url)
class CheckPayView(View):
def get(self, request):
params = request.GET.dict()
sign = params.pop('sign')
if alipay.verify(params, sign):
out_trade_no = params.get('out_trade_no', '')
register = Register.objects.get(out_trade_num=out_trade_no)
register.status = '待檢查'
register.isdelete = 0
register.save()
doctor_time_number = TimeNumber.objects.get(doctor_id=register.doctor_id)
consultation_hours_time = str(register.consultation_hours)[11:]
if consultation_hours_time == '08:00:00':
doctor_time_number.eight -= 1
elif consultation_hours_time == '09:00:00':
doctor_time_number.nine -= 1
elif consultation_hours_time == '10:00:00':
doctor_time_number.ten -= 1
elif consultation_hours_time == '11:00:00':
doctor_time_number.eleven -= 1
elif consultation_hours_time == '14:00:00':
doctor_time_number.fourteen -= 1
elif consultation_hours_time == '15:00:00':
doctor_time_number.fifteen -= 1
elif consultation_hours_time == '16:00:00':
doctor_time_number.sixteen -= 1
elif consultation_hours_time == '17:00:00':
doctor_time_number.seventeen -= 1
doctor_time_number.save()
return HttpResponseRedirect('/patientshowregistration/')
out_trade_no = params.get('out_trade_no', '')
register = Register.objects.get(out_trade_num=out_trade_no)
register.isdelete = 1
register.save()
return HttpResponseRedirect('/choosedepartment/')
class PatientShowRegistrationView(View):
'''患者展示掛號信息'''
def get(self, request):
patient = request.session.get('patient')
register_list = patient.register_set.order_by('consultation_hours').filter(
Q(isdelete=False, status='待檢查') | Q(isdelete=False, status='已檢查')).all()
return render(request, 'patientshowregistration.html', {
'register_list': register_list})
class GuideView(View):
def get(self, request):
return render(request, 'guide.html')
class TrafficView(View):
def get(self, request):
return render(request, 'traffic.html')
class DoctorCenterView(View):
'''醫生界面'''
def get(self, request):
doctor = request.session.get('doctor', '')
return render(request, 'doctorcenter.html', {
'doctor_name': doctor.name})
class DoctorShowRegistrationView(View):
'''醫生展示掛號信息'''
def get(self, request):
doctor = request.session.get('doctor')
try:
register_list = doctor.register_set.order_by('consultation_hours').filter(isdelete=0, status='待檢查').all()
except:
register_list = []
return render(request, 'doctorshowregistration.html', {
'register_list': register_list})
def post(self, request):
register_id = request.POST.get('register_id', '')
register = Register.objects.get(id=register_id)
register.status = '已檢查'
register.save()
doctor = request.session.get('doctor')
try:
register_list = doctor.register_set.order_by('consultation_hours').filter(isdelete=0, status='待檢查').all()
except:
register_list = []
return render(request, 'doctorshowregistration.html', {
'register_list': register_list})

setting.py

""" Django settings for hospital_registration_system project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-m*[email protected]!_29#[email protected]@56dc(#)&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'simpleui',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# myapp
'hospital',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'hospital_registration_system.urls'
TEMPLATES = [
{

'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {

'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'hospital_registration_system.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql',
'NAME': 'hospital_registration_system',
'HOST': '127.0.0.1',
'POST': '3306',
"USER": 'root',
"PASSWORD": 'sxing86'
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{

'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{

'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{

'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{

'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = False # 我遇到個問題 正確的時間存進數據庫後時間錯了 把這個變量改為False就解決了
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static').replace('\\','/'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# global_settings
CACHES = {

'default': {

'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
'session-redis': {

"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/2",
}
}
SESSION_CACHE_ALIAS = 'session-redis'
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

完整程序代碼下載地址:Python版醫院掛號系統源代碼
更多Python源代碼請關注:


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved