分类 编程/笔记 下的文章

Flask 是 Python 的一款轻量化Web框架,使用Flask可以快速完成Web应用的开发。

1 安装

Pip 方式:

pip install flask

Apt方式:

sudo apt-get install python-flask

在pip安装不了时使用apt强制安装

2 一个最小的应用

from flask import Flask #引用
app = Flask(__name__)

@app.route('/') #路由
def hello_world():
    return 'Hello World!' #返回

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=80) #全IP访问,80端口

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import urllib2
import json
args = sys.argv
city = args[1]
a = "http://www.sojson.com/open/api/weather/json.shtml?city=" + city
page = urllib2.urlopen(a, timeout=10)
data = page.read()
sj = json.loads(data)
print "天气数据(今天)"
print "---------------------------------------------"
print len(data)
print "---------------------------------------------"
print '响应:'
print sj['status']
print "---------------------------------------------"
print '城市:'
print city
print '最低气温:'
print sj['data']['forecast'][0]['low']
print '最高气温:'
print sj['data']['forecast'][0]['high']
print '天气:'
print sj['data']['forecast'][0]['type']
print '建议:'
print sj['data']['ganmao']
print "---------------------------------------------"
print 'json:'
print data

#如果想要明天的就将[0]改为[1],后天以此类推,范围:0-4
#获取昨天,如最低温度:sj['yesterday']['low'],参数可以在调试中找
#数据来源:http://www.sojson.com/api/weather.html
#频繁调用会导致封禁

用于简单演示JS的AJAX,使用Nodejs做服务端。

1.服务端源码(与这篇文章一样)

var http = require('http');//引用模块
var os = require('os');
var netdev = "wlan0";//网卡名
http.createServer(function (req, res) {
    var net = os.networkInterfaces();
    res.writeHead(200, {'Content-Type': 'application/json'});//Http响应头
    res.write("["+JSON.stringify({//生成json数据
        hostname:os.hostname(),
        platform:os.arch()+"-"+os.platform()+os.release(),
        uptime:os.uptime().toFixed(0),//系统运行时间取整
        load:os.loadavg(),
        totalram:(os.totalmem()/1024).toFixed(0),
        freeram:(os.freemem()/1024).toFixed(0),
    }));
    //网卡信息
    res.end(","+JSON.stringify({//生成json数据
        address:net[netdev][0]["address"],
        family:net[netdev][0]["family"],
        internal:net[netdev][0]["internal"]
    })+"]");
}).listen(80);//监听端口
console.log('Server running at http://192.168.3.184');

2.HTML源码

<script>
function getinfo(){
    http=new XMLHttpRequest(); //AJAX
    http.onreadystatechange=function() {
        if (http.readyState==4){
            if(http.status==200){
                var info = JSON.parse(http.responseText); //转换为JSON对象
                document.getElementById("ram").innerHTML=(info['freeram']/1024).toFixed(0)+'\/'+(info['totalram']/1024).toFixed(0)+"MB";
                document.getElementById("time").innerHTML=(info["uptime"]/60).toFixed(2)+'min';
                setInterval(function(){getinfo();},1500); //定时刷新(1.5s)
        }}}
    http.open("GET","/get",true); //连接
    http.send(null);
}
</script>
<body onload = getinfo()>
    <div align="center" id="l">设备信息</div>
    <div align="center">
        <table width="46%" id="tb">
            <tbody>
                <tr>
                    <th width="33%">设备</th>
                    <th width="34%">值</th>
                    <th width="33%">操作</th>
                </tr>
                <tr bgcolor="#FFFFFF">
                    <td>内存</td>
                    <td id='ram'>ram.value</td>
                    <td><!--<a href="on1"><button type="button1">开启</button></a><a href="off1"><button type="button4">关闭</button></a>-->-</td>
                </tr>
                <tr bgcolor="#FFFFFF">
                    <td>运行时间</td>
                    <td id='time'>time.value</td>
                    <td><!--<a href="on2"><button type="button2">开启</button></a><a href="off2"><button type="button5">关闭</button></a>-->-</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>

215_1.png

1.使用OpenSSL来为自己签发证书

#1 生成私钥
root@one:~/nodejs/CA# openssl genrsa 1024 > /pathway/private.pem
-bash: /pathway/private.pem: No such file or directory
root@orangepione:~/nodejs/CA# openssl genrsa 1024 > private.pem
Generating RSA private key, 1024 bit long modulus
..++++++
...............++++++
e is 65537 (0x10001)
#2 生成签发请求
root@one:~/nodejs/CA# openssl req -new -key private.pem -out csr.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:192.168.3.199
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
#3 提交签发
root@one:~/nodejs/CA# openssl x509 -req -days 365 -in csr.csr -signkey private.pem -out ca.crt
Signature ok
subject=/C=AU/ST=Some-State/L=/O=Internet Widgits Pty Ltd/OU=/CN=192.168.3.199
Getting Private key

2.服务端代码

var https = require('https');//引用https模块
var fs = require('fs');

var options = {
    key: fs.readFileSync('./CA/private.pem'),//私钥
    cert: fs.readFileSync('./CA/ca.crt')//证书
};

https.createServer(options,function(req,res){
    res.writeHead(200);//200响应
    res.end('hello world\n');//发送数据
}).listen(443);//监听默认的https端口

3.效果

212_1.png

由于是自签名证书,所以游览器显示不安全的连接是正常的。

学习了Nodejs的Post后写的一个非常简易的留言板。

一共三个文件:main.js(主程序),index.html(页面模板),input.txt(留言内容)。

var http = require('http');
var fs = require("fs");
var querystring = require('querystring');
http.createServer(function (req, res) {
    var post = '';
    req.on('data',function(chunk){
    post += chunk;//接收来自游览器的Post信息
    console.log(chunk);
    })
    req.on('end',function(){
        post = querystring.parse(post);//Post数据转换
        console.log('post:',post);
        res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});//请求头,一定要加,否则游览器访问会变成下载这个网页
        var data = fs.readFileSync('index.html');//同步读取
        if(post.id && post.user && post.text){//判断数据是否为空
            if(input(post.id,post.user,post.text) != -1){//判断报错
                res.write('感谢反馈!');
            }else{
                res.write('ERROR');
            }
        }else{
            res.write(data.toString());//返回表单
        }
        res.end();
    });
}).listen(80);
function input(id,user,text){
    var data = fs.readFileSync('input.txt');//同步读取
    data += JSON.stringify({'id':id,'user':user,'text':text});//以JSON的方式存储信息,input.txt必须存在,否则报错
    data += '\n';
    fs.writeFile('input.txt',data,{flag:'w',encoding:'utf-8',mode:'0666'},function(err){
     if(err){
         return -1;
     }});
}

175-1.png

初学Nodejs的练手之作,可能有细节处理不好。

代码还是比较简单的,用了oshttp模块,返回json数据。

var http = require('http');//引用模块
var os = require('os');
var netdev = "wlan0";//网卡名
http.createServer(function (req, res) {
    var net = os.networkInterfaces();
    res.writeHead(200, {'Content-Type': 'application/json'});//Http响应头
    res.write("["+JSON.stringify({//生成json数据
        hostname:os.hostname(),
        platform:os.arch()+"-"+os.platform()+os.release(),
        uptime:os.uptime().toFixed(0),//系统运行时间取整
        load:os.loadavg(),
        totalram:(os.totalmem()/1024).toFixed(0),
        freeram:(os.freemem()/1024).toFixed(0),
    }));
    //网卡信息
    res.end(","+JSON.stringify({//生成json数据
        address:net[netdev][0]["address"],
        family:net[netdev][0]["family"],
        internal:net[netdev][0]["internal"]
    })+"]");
}).listen(80);//监听端口
console.log('Server running at http://192.168.3.184');


84-3.png