1

s11 day 101 python Linux环境安装 与路飞项目支付功能

 

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
url(r'^buy/(?P<gid>\d+)/', views.buy),
url(r'^check_order/', views.check_order),
url(r'^show/', views.show),
url(r'^order_list/', views.order_list),
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^buy/(?P<gid>\d+)/', views.buy),
    url(r'^check_order/', views.check_order),
    url(r'^show/', views.show),
    url(r'^order_list/', views.order_list),

 

一、安装 python3  

 

1. 下载python 源包

  网址:https://www.python.org/downloads/release/python-362/

  下载地址:https://www.python.org/ftp/python/3.6.2/Python-3.6.2.tgz

2. 安装python前的库环境,非常重要

yum install gcc patch libffi-devel python-devel  zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel -y

3. 下载, 解压安装包

wget https://www.python.org/ftp/python/3.4.7/Python-3.4.7.tar.xz
xz -d Python-3.4.7.tar.xz
tar -xf Python-3.4.7.tar

4. 切换到python3 的目录

cd Python-3.4

5. 生成编译脚本

./configure --prefix=/opt/python37

6. 编译

make

7.编译成功后,编译安装

make install

8. 切换已安装好的python3.7目录

cd /opt/python37/

9.查看python3.7的可执行脚本文件

ls bin 

10. 执行python3.7解释器

 

  1. 绝对路径的执行方法一、

/opt/python37/bin/python3.7

  2. 相对路径的执行方法二、

bin/python3.7

  3. 添加环境变量

    1.  添加软连接(用法)

      ln -s  源文件路径  目标文件路径

    2.添加软连接

      

ln -s /opt/python37/bin/python3.7 /usr/local/bin/python3



ln -s /opt/python37/bin/pip3 /usr/local/bin/pip3  pip3 添加软连接

 

 

二、又装了一遍 3.5.6 

1. 通过xft 下载 3.5.6 到 opt目录下 ,然后解压 

 

 

 

 编译完成后 ,make  ,make install

 

 

 安装django

[root@python10 ~]# pip3 install django==1.1

 

 

装完 django后创建一个软连接

 

ln -s /opt/python35/bin/django-admin /usr/local/bin/django-admi

 

然后新建一个项目

 django-admin startproject mysite  #创建在一个目录下 
dadmin-admin startapp app01

进入目录运行

 python3 manage.py runserver 127.0.0.1:8000

 

 

 

 

在Linux
    安装Python3.5.6详细文档!!!!
    
        1.安装相关依赖库(工具包)
            yum install gcc patch libffi-devel python-devel  zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel -y
        2.下载python3的源代码(在linux终端下输入命令)
        切换/opt目录
        cd /opt
        #下载python3.5.6源代码
        wget https://www.python.org/ftp/python/3.5.6/Python-3.5.6.tgz
            #python源码的下载地址。(全都在这了)
            https://www.python.org/ftp/python/
        3.解压缩源代码
            tar -xf Python-3.5.6.tgz
            (出现Python-3.5.64.切换python3.5的源代码目录
        cd Python-3.5.6
        5.生成编译脚本(指定安装目录)
        ./configure --prefix=/opt/python35
        6.编译
        make
        7.编译成功后,编译安装
        make install
        8.切换已经装好的python3.5目录
        cd /opt/python35/
        9.查看python3.5的可执行脚本文件
            [root@localhost python35]# ls bin/
        10.执行python3.5解释器
            1.绝对路径执行方式一
                /opt/python35/bin/python3.5
            2.相对路径执行方式二
                [root@localhost python35]# bin/python3.5
            3.添加环境变量
                1.添加软连接(用法)
                ln -s 原文件路径 目标文件路径
                2.添加软连接
                (绝对路径)ln -s /opt/python35/bin/python3.5 /usr/local/bin/python3
            4.添加pip3软连接
            ln -s /opt/python35/bin/pip3 /usr/local/bin/pip3
            
            5.查看pip3版本
            pip3 -V
                pip 10.0.1 from /opt/python35/lib/python3.5/site-packages/pip (python 3.5)

            
                
                
tip:
    python3.5软连接:
        ln -s /opt/python35/bin/python3.5 /usr/local/bin/python3.5
        
    删除python3.5的软连接:
        rm -rf /usr/local/bin/python3
安装django 
    1.安装django方式1
            pip3 install django==1.11
        方式2:
            python3 -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple django==1.11
    
        卸载django
            pip3 uninstall django
        
        更新pip工具
            pip3 install --upgrade pip
    2.安装好django1.11之后,配置软连接
            ln -s /opt/python35/bin/django-admin      /usr/local/bin/django-admin

    3.启动django
        vi settings.py
            写入 ALLOWED_HOSTS = ['*']
        启动django
        python3.5 manage.py runserver 0.0.0.0:8000

    4.windows访问linux的ip地址+端口
        x.x.x.x:8000


代码上传并运行
    1.windows下写代码
        修改相应的配置文件
    2.测试bug!!!!
    3.通过xftp传输到服务器
    4.启动项目
    
View Code

 

 

一下文章为连接出处 

https://blog.csdn.net/wh211212/article/details/52992413

 

1. 安装django 

[1]  安装一些软件包    .
# install from EPEL
[root@linuxprobe ~]# yum --enablerepo=epel -y install python-virtualenv

[2]  在Virtualenv环境下安装Django,它可以为任何普通用户,这里使用root,建议使用普通用户。   
[root@linuxprobe ~]$ virtualenv venv
[root@linuxprobe ~]$ cd ~/venv
[root@linuxprobe venv]$ source bin/activate
(venv)[root@linuxprobe venv]$ pip install django
Downloading/unpacking django
  Downloading Django-1.10.2.tar.gz (7.7MB): 7.7MB downloaded
  Running setup.py egg_info for package django

    no previously-included directories found matching 'django/contrib/admin/bin'
    warning: no previously-included files matching '__pycache__' found anywhere in distribution
Installing collected packages: django
  Running setup.py install for django

    no previously-included directories found matching 'django/contrib/admin/bin'
    warning: no previously-included files matching '__pycache__' found anywhere in distribution
    changing mode of build/scripts-2.7/django-admin.py from 644 to 755
    changing mode of /root/venv/bin/django-admin.py to 755
    Installing django-admin script to /root/venv/bin
Successfully installed django
Cleaning up...
# 上面的警告不是问题
(venv)[root@linuxprobe venv]# django-admin --version
1.10.2
# 退出virtualenv
(venv)[root@linuxprobe venv]# deactivate

 

[3] 创建测试项目
[root@linuxprobe ~]$ cd ~/venv 
[root@linuxprobe venv]$ source bin/activate
# create "testproject"
(venv)[root@linuxprobe venv]$ django-admin startproject testproject 
(venv)[root@linuxprobe venv]$ cd testproject 
# configure database (default is SQLite)
(venv)[root@linuxprobe testproject]$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying sessions.0001_initial... OK
# create admin user
(venv)[root@linuxprobe testproject]# python manage.py createsuperuser
Username (leave blank to use 'root'): root
Email address: root@linuxprobe.org
Password: 
Password (again): 
Superuser created successfully.
# start server
(venv)[root@linuxprobe testproject]# python manage.py runserver 0.0.0.0:8000
Performing system checks...

System check identified no issues (0 silenced).
October 31, 2016 - 14:03:16
Django version 1.10.2, using settings 'testproject.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

 

[4]从客户端计算机访问“http://(服务器的主机名或IP地址):8000 /”。如果以下网站正常显示,表示启动成功。 

 

[5]用户管理网站可以在“http://(服务器的主机名或IP地址):8000 / admin”

 

二、项目逻辑

 

1.账号设置

 

支付宝沙箱环境登录 :

https://openhome.alipay.com/platform/appDaily.htm?tab=info

账号:

 

 

 

 

商家账号:

 

 

买家信息:

 

 

 

2. 

引入sdk

from datetime import datetime
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from urllib.parse import quote_plus
from urllib.parse import urlparse, parse_qs
from base64 import decodebytes, encodebytes
import json


class AliPay(object):
    """
    支付宝支付接口(PC端支付接口)
    """

    def __init__(self, appid, app_notify_url, app_private_key_path,
                 alipay_public_key_path, return_url, debug=False):
        self.appid = appid
        self.app_notify_url = app_notify_url
        self.app_private_key_path = app_private_key_path
        self.app_private_key = None
        self.return_url = return_url
        with open(self.app_private_key_path) as fp:
            self.app_private_key = RSA.importKey(fp.read())
        self.alipay_public_key_path = alipay_public_key_path
        with open(self.alipay_public_key_path) as fp:
            self.alipay_public_key = RSA.importKey(fp.read())

        if debug is True:
            self.__gateway = "https://openapi.alipaydev.com/gateway.do"
        else:
            self.__gateway = "https://openapi.alipay.com/gateway.do"

    def direct_pay(self, subject, out_trade_no, total_amount, return_url=None, **kwargs):
        biz_content = {
            "subject": subject,
            "out_trade_no": out_trade_no,
            "total_amount": total_amount,
            "product_code": "FAST_INSTANT_TRADE_PAY",
            # "qr_pay_mode":4
        }

        biz_content.update(kwargs)
        data = self.build_body("alipay.trade.page.pay", biz_content, self.return_url)
        return self.sign_data(data)

    def build_body(self, method, biz_content, return_url=None):
        data = {
            "app_id": self.appid,
            "method": method,
            "charset": "utf-8",
            "sign_type": "RSA2",
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "version": "1.0",
            "biz_content": biz_content
        }

        if return_url is not None:
            data["notify_url"] = self.app_notify_url
            data["return_url"] = self.return_url

        return data

    def sign_data(self, data):
        data.pop("sign", None)
        # 排序后的字符串
        unsigned_items = self.ordered_data(data)
        unsigned_string = "&".join("{0}={1}".format(k, v) for k, v in unsigned_items)
        sign = self.sign(unsigned_string.encode("utf-8"))
        # ordered_items = self.ordered_data(data)
        quoted_string = "&".join("{0}={1}".format(k, quote_plus(v)) for k, v in unsigned_items)

        # 获得最终的订单信息字符串
        signed_string = quoted_string + "&sign=" + quote_plus(sign)
        return signed_string

    def ordered_data(self, data):
        complex_keys = []
        for key, value in data.items():
            if isinstance(value, dict):
                complex_keys.append(key)

        # 将字典类型的数据dump出来
        for key in complex_keys:
            data[key] = json.dumps(data[key], separators=(',', ':'))

        return sorted([(k, v) for k, v in data.items()])

    def sign(self, unsigned_string):
        # 开始计算签名
        key = self.app_private_key
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(SHA256.new(unsigned_string))
        # base64 编码,转换为unicode表示并移除回车
        sign = encodebytes(signature).decode("utf8").replace("\n", "")
        return sign

    def _verify(self, raw_content, signature):
        # 开始计算签名
        key = self.alipay_public_key
        signer = PKCS1_v1_5.new(key)
        digest = SHA256.new()
        digest.update(raw_content.encode("utf8"))
        if signer.verify(digest, decodebytes(signature.encode("utf8"))):
            return True
        return False

    def verify(self, data, signature):
        if "sign_type" in data:
            sign_type = data.pop("sign_type")
        # 排序后的字符串
        unsigned_items = self.ordered_data(data)
        message = "&".join(u"{}={}".format(k, v) for k, v in unsigned_items)
        return self._verify(message, signature)
View Code

 

 

安装一个组件 依赖加密的模块:

pip3 install pycryptodome

 导入SDK ,叫做utils

 

models

from django.db import models

# Create your models here.
class Goods(models.Model):
    name =models.CharField(max_length=32)
    price =models.FloatField()
    
class Order(models.Model):
    num = models.CharField(max_length=64)
    goods =models.ForeignKey(to="Goods")
    status_choice =(
        (1,"未支付"),
        (2,"已支付"),
    )
    status = models.IntegerField(choices= status_choice,default=1)

 

index页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>xx</title>
</head>
<body>
    <ul>
        {% for row in goods_list %}
            <li>{{ row.name }},价格:{{ row.price }}   <a href="/buy/{{ row.id }}/">购买</a></li>
        {% endfor %}
    </ul>
</body>
</html>

 

url

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^buy/(?P<gid>\d+)/', views.buy),
    url(r'^check_order/', views.check_order),
    url(r'^show/', views.show),
    url(r'^order_list/', views.order_list),


]

 

 

order_list

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <table border="1">
        {% for item in orders %}
        <tr>
            <td>{{ item.id }}</td>
            <td>{{ item.num }}</td>
            <td>{{ item.goods.name }}</td>
            <td>{{ item.get_status_display }}</td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>

 

 

views视图逻辑

from django.shortcuts import render, HttpResponse, redirect
# Create your views here.
from app01 import models
from utils.pay import AliPay
import uuid
def index(request):
    goods_list = models.Goods.objects.all()
    # return  render(request,"index.html",{"godds_list":goods_list})
    return render(request, 'index.html', {'goods_list': goods_list})

def buy(request, gid):
    # 去购买并支付
    obj = models.Goods.objects.get(pk=gid)
    print(obj.name, obj.price)

    # 生成订单(未支付)
    no = str(uuid.uuid4())
    models.Order.objects.create(num=no, goods_id=obj.id)

    # 根据
    #   APPID
    #   支付宝网关
    #   公钥和私钥
    # 生成要跳转的地址
    # 沙箱环境地址:https://openhome.alipay.com/platform/appDaily.htm?tab=info
    alipay = AliPay(
        appid="2016091700528853",

        app_notify_url="http://132.232.55.209/check_order/",  # POST,发送支付状态信息
        return_url="http:///132.232.55.209/show/",  # GET,将用户浏览器地址重定向回原网站

        app_private_key_path="keys/app_private_2048.txt",
        alipay_public_key_path="keys/alipay_public_2048.txt",

        debug=True,  # 默认True测试环境、False正式环境
    )

    query_params = alipay.direct_pay(
        subject=obj.name,  # 商品简单描述
        out_trade_no=no,  # 商户订单号
        total_amount=obj.price,  # 交易金额(单位: 元 保留俩位小数)
    )

    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)

    return redirect(pay_url)

def check_order(request):
    """
    POST请求,支付宝通知支付信息,我们修改订单状态
    :param request:
    :return:
    """
    if request.method == 'POST':
        alipay = AliPay(
            appid="2016091700528853",
            app_notify_url="http://132.232.55.209/check_order/",  # POST,发送支付状态信息
            return_url="http:///132.232.55.209/show/",  # GET,将用户浏览器地址重定向回原网站
            app_private_key_path="keys/app_private_2048.txt",
            alipay_public_key_path="keys/alipay_public_2048.txt",
            debug=True,  # 默认True测试环境、False正式环境
        )

        from urllib.parse import parse_qs
        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)

        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]
        sign = post_dict.pop('sign', None)
        status = alipay.verify(post_dict, sign)
        if status:
            # 支付成功,获取订单号将订单状态更新
            out_trade_no = post_dict['out_trade_no']
            models.Order.objects.filter(no=out_trade_no).update(status=2)
            return HttpResponse('success')
        else:
            return HttpResponse('支持失败')



    else:
        return HttpResponse('只支持POST请求')

def show(request):
    """
    回到我们页面
    :param request:
    :return:
    """

    if request.method == "GET":
        alipay = AliPay(
            appid="2016082500309412",
            app_notify_url="http://47.98.134.86:8805/check_order/",  # POST,发送支付状态信息
            return_url="http:///47.98.134.86:8805/show/",  # GET,将用户浏览器地址重定向回原网站
            app_private_key_path="keys/app_private_2048.txt",
            alipay_public_key_path="keys/alipay_public_2048.txt",
            debug=True,  # 默认True测试环境、False正式环境
        )

        params = request.GET.dict()
        sign = params.pop('sign', None)
        status = alipay.verify(params, sign)
        if status:
            return HttpResponse('支付成功')
        else:
            return HttpResponse('失败')
    else:
        return HttpResponse('只支持GET请求')

#查看订单的界面
def order_list(request):
    """
    查看所有订单状态
    :param request:
    :return:
    """
    orders = models.Order.objects.all()
    for items in orders:
        print(items.num,"====>",items.goods.name,)
    return render(request, 'order_list.html', {'orders': orders})

 

posted @ 2018-08-10 15:53  萌哥-爱学习  阅读(353)  评论(0编辑  收藏  举报