api接口详解,restful风格接口

作者: 韦德国际1946手机版  发布:2019-05-28

前言

java api开垦 restful风格接口
韦德国际1946手机版 1
新人 怎么不一致请求方式 是图表上这样么,来大神引导下啊。

安装

pip install djangorestframework

转 http://www.yiichina.com/tutorial/1143
yii2中restful url访问配置, 登陆接口access-token验证类 [ 2.0 版本 ]

登陆接口access-token验证类
Controller下新建BaseActiveController.php

<?php
/**
 *接口登陆验证
 * @author 爱博
 * 1.0
 *
 */
namespace backendcontrollers;

use yiifiltersauthCompositeAuth;
use yiifiltersauthHttpBasicAuth;
use yiifiltersauthHttpBearerAuth;
use yiifiltersauthQueryParamAuth;
use yiifiltersCors;
use yiifiltersRateLimiter;
use yiirestController;
use Yii;

class BaseActiveController extends Controller
{
    public $modelClass = 'commonmodelsuser';

    public $post = null;
    public $get = null;
    public $user = null;
    public $userId = null;

    public function init()
    {
        parent::init();

        Yii::$app->user->enableSession = false;
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
           //     HttpBasicAuth::className(),
           //     HttpBearerAuth::className(),
                QueryParamAuth::className(),
            ],
        ];


      //  数据返回类型设置
        //$behaviors['contentNegotiator']['formats']['application/json'] = 'json';
       //$behaviors['contentNegotiator']['formats']['application/xml'] = 'json';

        return $behaviors;
    }


    public function beforeAction($action)
    {
        parent::beforeAction($action);

        $this->post = yii::$app->request->post();
        $this->get = yii::$app->request->get();
        $this->user = yii::$app->user->identity;
        $this->userId = Yii::$app->user->id;

        return $action;
    }


} 

下边新建 UserController.php

<?php
namespace backendcontrollers;
use Yii;
use yiifiltersauthCompositeAuth;
use yiifiltersauthQueryParamAuth;
use yiidataActiveDataProvider;
use yiihelpersJson;
use commonmodelsLoginForm;

class UserController extends BaseActiveController
{
    /**
     * 判断用户登录信息,并返回结果。
     * @author   <sang.jiyu>
     */
    public function actionIndex()
    {
        if(Yii::$app->user->isGuest){
            $data=array(
                'code'=>100,
                'message'=>'用户未登录',
                'data'=>'',
            );
        }else{
            $data=array(
                'code'=>200,
                'message'=>'用户已经登录',
                'data'=>array(
                    'user_id'=>Yii::$app->user->id,
                    'user_name'=>isset(Yii::$app->user->identity->username) ? Yii::$app->user->identity->username : '',
                ),
            );
        }
        echo json_encode($data);exit;
    }

}

目录common/models下新建 User.php

<?php
namespace commonmodels;

use Yii;
use yiibaseNotSupportedException;
use yiibehaviorsTimestampBehavior;
use yiidbActiveRecord;
use yiiwebIdentityInterface;

/**
 * User model
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property string $auth_key
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
* @property integer  $curr_login_ip
 * @property integer $curr_login_at
 * @property string $password write-only password
 */



class User extends ActiveRecord implements IdentityInterface
{

    public $curr_login_at;
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;


    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    # 生成access_token  
    public function generateAccessToken()  
    {  
        $this->access_token = Yii::$app->security->generateRandomString();  
    }  

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }




    public static function findIdentityByAccessToken($token, $type = null)
    {

        return static::findOne(['access_token' => $token]);
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_')   1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp   $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {


        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}

在新建LoginForm.php

<?php
namespace commonmodels;

use Yii;
use yiibaseModel;

/**
 * Login form
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;

    private $_user;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    /**
     * Finds user by username
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
}

http://localhost/yii2/backend/web/index.php?r=user/index&access-token=rMwh_EnqAc0qEPTfzb66BlGtSqoF15sg
没有作美化,大家自己处理一下吧,注意这个rMwh_EnqAc0qEPTfzb66BlGtSqoF15sg内容为数据库里的access-token这个内容里的值
返回内容为

{"code":200,"message":"u7528u6237u5df2u7ecfu767bu5f55","data":{"user_id":"1","user_name":"terry"}}

返回这个内容就成功了

下边完成登陆用户名和密码验证生成access-token的内容
在controllers这个目录下新建SiteController.php

<?php
/**
* 
*登陆接口access-token验证类
* @author 爱博
* 1.0
*
*
*/

namespace backendcontrollers;

use Yii;
use backendmodelsformsLoginForm;
use commonlibHelper;
use yiibaseException;
use yiibaseInvalidValueException;
use yiibaseUserException;
use yiiwebErrorAction;
use yiiwebHttpException;
use yiirestController;

class SiteController extends Controller
{

    public $modelClass = 'commonmodelsuser';
    public function behaviors()
    {
       $behaviors = parent::behaviors();
       // unset($behaviors['authenticator']);
        return $behaviors;
    }

    protected function verbs()
    {
        $verbs = parent::verbs();
      //  $verbs['index'] = ['POST'];
        return $verbs;
    }

    public function actionLogin()
    {

        $loginModel = new LoginForm();
        $loginModel->load([$loginModel->formName() => yii::$app->request->get()]);

         if ($loginModel->validate()) {
            $rs = $loginModel->login();

            return Helper::format_data($rs);
        } else {
            return Helper::format_data($loginModel->getErrors(), HTTP_STATUS_401);
        }
    }
}

运行http://localhost/yii2/backend/web/index.php?r=site/login&password=rasmuslerdorf&username=terry

Use of undefined constant HTTP_STATUS_200 - assumed 'HTTP_STATUS_200'

返回这个内容就成功了

用Python怎样写3个接口呢,首先得要有数据,能够用我们在网址上爬的数量,在上1篇小说中写了怎么用Python爬虫,有乐趣的可以看看://www.jb51.net/article/141661.htm

settings配置

INSTALLED_APPS = [ 'rest_framework', 'rest_framework.authtoken',]

 

多量的数据保存到数据库比较便利。小编用的pymsql,pymsql是Python中操作MySQL的模块,其选用格局和MySQLdb大概等同。但眼下在python3.x中,PyMySQL代替了MySQLdb。

api.py

app目录下新建api.py

from website.models import Video
from rest_framework import serializers, status
from rest_framework.response import Response
from rest_framework.decorators import api_view, authentication_classes
from rest_framework.authentication import TokenAuthentication

class VideoSerializer(serializers.ModelSerializer):
    title = serializers.CharField(min_length=1)
    class Meta:
        model = Video
        fields = '__all__'

@api_view(['GET', 'POST'])
def video(request):
    print(request.user)
    print('$'*45)
    if request.method == 'GET':
        video_list = Video.objects.order_by('-id')
        serializer = VideoSerializer(video_list, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = VideoSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        body = { 'body': serializer.errors,            'msg': '40001'        }
        return Response(body, status=status.HTTP_400_BAD_REQUEST)

数据库如下:

韦德国际1946手机版 ,一.接连数据库

urls.py

/*
Navicat MySQL Data Transfer

# 连接数据库,需指定charset否则可能会报错
db = pymysql.connect(host="localhost", user="root", password="123", db="mysql", charset="utf8mb4")
cursor = db.cursor() # 创建一个游标对象

Source Server : localhost
Source Server Version : 50553
Source Host : localhost:3306
Source Database : oauth2

二.创立数据库

Target Server Type : MYSQL
api接口详解,restful风格接口。Target Server Version : 50553
File Encoding : 65001

cursor.execute("DROP TABLE IF EXISTS meizi_meizis") # 如果表存在则删除
 # 创建表sql语句
 createTab = """create table meizi_meizis(
 id int primary key auto_increment,
 mid varchar(10) not null,
 title varchar(50),
 picname varchar(10),
 page_url varchar(50),
 img_url varchar(50)
 );"""
 cursor.execute(createTab) # 执行创建数据表操作

Date: 2017-01-16 13:57:48
*/

三.爬取多少

SET FOREIGN_KEY_CHECKS=0;

def html(self, href, title):
 lists = []
 meiziid = href.split('/')[-1]
 html = self.request(href)
 max_span = BeautifulSoup(html.text, 'lxml').find('div', class_='pagenavi').find_all('span')[-2].get_text()
 for page in range(1, int(max_span)   1):
 meizi = {}
 page_url = href   '/'   str(page)
 img_html = self.request(page_url)
 img_url = BeautifulSoup(img_html.text, 'lxml').find('div', class_='main-image').find('img')['src']
 picname = img_url[-9:-4]
 meizi['meiziid'] = meiziid
 meizi['title'] = title
 meizi['picname'] = picname
 meizi['page_url'] = page_url
 meizi['img_url'] = img_url
 lists.append(meizi) # 保存到返回数组中
 return lists

四.保留到数据库

-- Table structure for mxq_guide

def all_url(self, url):
 html = self.request(url)
 all_a = BeautifulSoup(html.text, 'lxml').find('div', class_='all').find_all('a')
 for index, a in enumerate(all_a):
 title = a.get_text()
 href = a['href']
 lists = self.html(href, title)
 for i in lists:
 # print(i['meiziid'], i['title'], i['picname'], i['page_url'], i['img_url'])
 # 插入数据到数据库sql语句,%s用作字符串占位
 sql = "INSERT INTO `meizi_meizis`(`mid`,`title`,`picname`,`page_url`,`img_url`) VALUES(%s,%s,%s,%s,%s)"
 try:
  cursor.execute(sql, (i['meiziid'], i['title'], i['picname'], i['page_url'], i['img_url']))
  db.commit()
  print(i[0]   " is success")
 except:
  db.rollback()
 db.close() # 关闭数据库

5.创建Web工程

DROP TABLE IF EXISTS mxq_guide;
CREATE TABLE mxq_guide (
id int(11) NOT NULL,
imgurl varchar(255) DEFAULT NULL,
status smallint(2) DEFAULT NULL,
flag smallint(2) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

运营我们的爬虫,比比较快数据库表里就有数据了。


韦德国际1946手机版 2

-- Records of mxq_guide

接下来初阶写接口。小编是因而Django rest_framework来写的。


Django 是用Python开垦的3个无需付费开源的Web框架,能够用来神速搭建高性能,优雅的网址。Django 中提供了开支网址平常应用的模块,常见的代码都为你写好了,缩小重复的代码。

INSERT INTO mxq_guide VALUES ('0', 'ddd', '1', '1111');
INSERT INTO mxq_guide VALUES ('2', 'ssss', '1', '2222');
INSERT INTO mxq_guide VALUES ('3', '555', '4', '444');

Django 目录结构


urls.py

-- Table structure for user

网址入口,关联到相应的views.py中的二个函数(或许generic类),访问网站就相应二个函数。


views.py

DROP TABLE IF EXISTS user;
CREATE TABLE user (
id int(20) unsigned NOT NULL AUTO_INCREMENT,
username varchar(50) DEFAULT NULL COMMENT '用户名',
password_hash varchar(80) DEFAULT NULL COMMENT '密码',
password_reset_token varchar(60) DEFAULT NULL COMMENT '密码token',
email varchar(60) DEFAULT NULL COMMENT '邮箱',
auth_key varchar(60) DEFAULT NULL,
status int(5) DEFAULT NULL COMMENT '状态',
created_at int(1捌) DEFAULT NULL COMMENT '创造时间',
updated_at int(1八) DEFAULT NULL COMMENT '更新时间',
password varchar(50) DEFAULT NULL COMMENT '密码',
role varchar(50) DEFAULT NULL COMMENT 'role',
curr_login_at varchar(50) DEFAULT NULL,
curr_login_ip varchar(50) DEFAULT NULL,
access_token varchar(60) DEFAULT NULL,
login_count varchar(50) DEFAULT NULL,
allowance int(20) NOT NULL,
allowance_updated_at int(20) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY username (username),
UNIQUE KEY access_token (access_token)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

拍卖用户爆发的伸手,从urls.py中对应还原, 通过渲染templates中的网页可以将展现内容,比如登入后的用户名,用户请求的数额,输出到网页。


models.py

-- Records of user

与数据库操作相关,存入或读取数据时用到这几个,当然用不到数据库的时候 你可以不应用。


forms.py

INSERT INTO user VALUES ('1', 'terry', '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq', null, 'zqy234@126.com', 'pBJi3hyFsLsTuvUM9paFpWjYRatn3qwS', '10', '1441763620', '1484546128', null, null, '1484235121', '::1', 'qvuhh01lt4Q4GZnnLI2gdL1HwYR0nLWN', '17', '0', '1447318986');
INSERT INTO user VALUES ('2', 'terry1', '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq', null, 'zqy2341@126.com', 'wIvJk7dMm6PQ1dJFz8iUqJ1RfH6rsDTW', '10', '1441763906', '1484235959', null, null, '1484235121', '::1', '_ydI-L1lQQwKZzoOWzMOUjMZ-t1PcM4k', '2', '0', '0');
INSERT INTO user VALUES ('3', 'zqy', '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq', null, 'zqy23114@126.com', 'K-76pcy7gxceemxRI2IeN5g1EhLMaCj8', '10', '1442544183', '1442544183', null, 'moderator', null, null, null, null, '0', '0');
INSERT INTO user VALUES ('4', 'admin', '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq', null, 'zqy2342321@126.com', 'hZWOaamjHEsPtuJJVghFRdE2oTj7Qv8P', '10', '1446524232', '1446524232', null, null, null, null, null, null, '0', '0');

表单,用户在浏览器上输入数据交由,对数据的认证专门的职业以及输入框的改变等工作,当然你也得以不应用。

数据库

本文由韦德国际1946发布于韦德国际1946手机版,转载请注明出处:api接口详解,restful风格接口

关键词: 接口 风格 restful api 大数据 爬虫