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

Python網上商城源代碼,基於Django+MySQL+Redis,支持支付寶付款

編輯:Python

Python網上商城源代碼,基於Django+MySQL+Redis,支持支付寶付款,實現:用戶登錄注冊,商品展示,商品詳情界面,搜索商品,將不同尺寸顏色數量的商品加入購物車,購物車管理,地址管理,形成訂單,支付寶支付。
更改netshop裡settings的DATABASES。
要啟動支付功能時,去掉在order裡urls.py的兩條path前的注釋,以及views.py裡第54行和最後一行的注釋,填入支付寶公鑰、應用私鑰和appid。
程序運行截圖



核心程序代碼
setting.py

""" Django settings for netshop 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/ """
from pathlib import Path
import os
# 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-$kjc-+6u73ma^=xp7pf7)hspeb_9=++h+nb8hl&&uhjul%us!5'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# my app
'goods',
'userapp',
'cart',
'order',
'utils',
]
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 = 'netshop.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',
'userapp.mycontextprocessors.getUserInfo', # 不論模塊和應用都能共享
],
},
},
]
WSGI_APPLICATION = 'netshop.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql',
'NAME': 'netshop',
'HOST': '127.0.0.1',
'POST': '3306',
'USER': 'root',
'PASSWORD': ''
}
}
# 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 = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True # 看到視頻上有
USE_TZ = True
# 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\css'),
os.path.join(BASE_DIR,'static\js'),
os.path.join(BASE_DIR,'static\images'),
]
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/1",
}
}
SESSION_CACHE_ALIAS = 'session-redis'
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

goods/views.py

from django.shortcuts import render
# Create your views here.
from django.views import View
from goods.models import *
from django.core.paginator import Paginator
import math
class IndexView(View):
def get(self, request, cid=2, num=1, *args, **kwargs):
cid = int(cid)
num = int(num)
# 查詢所有類別信息
categorys = Category.objects.all().order_by('id')
# 查詢當前類別下的所有商品信息
goodsList = Goods.objects.filter(category_id=cid).order_by('id')
# 分頁 每頁顯示八條記錄
pager = Paginator(goodsList, 8)
# 獲取當前頁的數據
page_goodsList = pager.page(num)
# 每頁開始頁碼
begin = (num - int(math.ceil(10.0 / 2)))
if begin < 1:
begin = 1
# 每頁結束頁碼
end = begin + 9
if end > pager.num_pages:
end = pager.num_pages
if end <= 10:
begin = 1
else:
begin = end - 9
pagelist = range(begin, end + 1)
return render(request, 'index.html',
{
'categorys': categorys, 'goodsList': page_goodsList, 'currentcid': cid, 'pagelist': pagelist,
'currentNum': num})
def recommed_view(func): # 怎麼說呢 因為現在只有女裝的數據 其他的沒有 如果你單純浏覽女裝的東西 這方法相當於是歷史記錄了 但你浏覽別的類別就不會推薦女裝的東西了
def wrapper(detailView, request, goodsid, *args, **kwargs):
# 將存放在cookie中的goodsid獲取
cookie_str = request.COOKIES.get('recommend', '')
# 存放goodsID放在裡面
goodsidlist = [gid for gid in cookie_str.split() if gid.strip()]
# 最終需要獲取的推薦商品
goodsobjlist = [Goods.objects.get(id=gsid) for gsid in goodsidlist if
gsid != goodsid and Goods.objects.get(id=gsid).category_id == Goods.objects.get(id=goodsid).category_id][:4]
# id對象放在裡面就是id對應整個商品的屬性 查詢出來的是整個goodislist的所有對象,但是下面只顯示四個,列表切片就可以了
# 將 goodsliest 傳給get方法
response = func(detailView, request, goodsid, goodsobjlist, *args, **kwargs)
# 這個地方你可以理解為調用了get方法,然後返回給了浏覽器一個response對象了,只不過這個地方拿過來了,很基本的通用操作,注意一下
# 判斷 goodsid 是否存在goodsidlist中
if goodsid in goodsidlist:
goodsidlist.remove(goodsid)
goodsidlist.insert(0, goodsid)
else:
goodsidlist.insert(0, goodsid)
# 將goosidlist中的數據保存到cookid中
response.set_cookie('recommend', ' '.join('%s' % gsid for gsid in goodsidlist), max_age=3 * 24 * 60 * 60)
return response
return wrapper
class DetailView(View):
@recommed_view
def get(self, request, goodsid, recommendlist=[]):
goodsid = int(goodsid)
# 根據goodsid查詢商品詳情信息,(goods對象)
goods = Goods.objects.get(id=goodsid)
category = Category.objects.get(id=goods.category_id).cname
return render(request, 'detail.html', {
'goods': goods, 'recommendlist': recommendlist, 'category': category})
class SearchView(View):
def get(self, request, num=1, *args, **kwargs):
num = int(num)
search = request.GET.get('search', '')
goods = Goods.objects.filter(gname__contains=search)
return render(request, 'search.html', {
'goods': goods})

完整源代碼下載地址:Python網上商城源代碼
更多Python源代碼:


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