PIXNET Logo登入

互聯網 - 大數據

跳到主文

本部落格為互聯網熱門頭條訊息管理中心

部落格全站分類:生活綜合

  • 相簿
  • 部落格
  • 留言
  • 名片
  • 3月 09 週四 201720:32
  • Python第十三天 django 1.6 導入模板 定義數據模型 訪問數據庫 GET和POST方法 SimpleCMDB項目 urllib模塊 urllib2模塊 httplib模塊 django和web服務器整合 wsgi模塊 gunicorn模塊


文章出處
Python第十三天   django 1.6   導入模板   定義數據模型   訪問數據庫   GET和POST方法    SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊  django和web服務器整合  wsgi模塊   gunicorn模塊
 
 
目錄
Pycharm使用技巧(轉載)
Python第一天 安裝 shell 文件
Python第二天 變量 運算符與表達式 input()與raw_input()區別 字符編碼
Python第三天 序列 數據類型 數值 字符串 列表 元組 字典
Python第四天 流程控制 ifelse條件判斷 forwhile循環
Python第五天 文件訪問 for循環訪問文件 while循環訪問文件 字符串的startswith函數和split函數
Python第六天 類型轉換
Python第七天 函數 函數參數 函數變量 函數返回值 多類型傳值 冗余參數 函數遞歸調用 匿名函數 內置函數 列表表達式/列表重寫
Python第八天 模塊 包 全局變量和內置變量__name__ Python path
Python第九天 面向對象 類定義 類的屬性 類的方法 內部類 垃圾回收機制 類的繼承
Python第十天 print >> f,和fd.write()的區別 stdout的buffer 標準輸入 標準輸出 標準錯誤 重定向
Python第十一天 異常處理 glob模塊和shlex模塊 打開外部程序和subprocess模塊 subprocess類 Pipe管道 operator模塊 sorted函數 生成器 walk模塊 hashlib模塊
Python第十二天   收集主機信息   正則表達式   正則表達式  無名分組   有名分組
Python第十三天   django 1.6   導入模板   定義數據模型   訪問數據庫   GET和POST方法    SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊  django和web服務器整合  wsgi模塊   gunicorn模塊
Python第十四天 序列化  pickle模塊  cPickle模塊  JSON模塊  API的兩種格式
 
 
 
 
前端模板:(SmartAdmin)http://www.cnblogs.com/smartbooks/archive/2012/12/03/2799416.html
 
現在主流使用django 1.6
https://docs.djangoproject.com/en/1.7/faq/install/
 
MVC
M:models.py
V:templates 和views.py
C:urls.py
 
 
Django
Django的安裝
https://docs.djangoproject.com/en/1.6/
1、pip 安裝方式
pip install django==1.6.5
或
easy_install django
查看是否安裝成功
pip list
2、源碼安裝方式
下載tar.gz包
django的源碼包
https://pypi.python.org/pypi/Django
python setup.py install
中文文檔:
http://djangobook.py3k.cn/2.0/
# 驗證django版本
import django
print(django.get_version())
1.5.5
 
django-admin.py
/usr/bin/django-admin.py
/usr/lib/python2.6/site-packages/django/bin/django-admin.py
 


 
創建工程
首先創建一個工程目錄:
cd /data/www/
#web為項目名,在當前目錄下會新建一個web目錄
django-admin.py startproject web
settings.py當前工程的配置文件
urls.py:urls配置文件,MVC里面的C
__init__.py 說明當前是一個包,python可以引入這個目錄下的模塊
 
# 修改時區和語言
vim settings.py
TIME_ZONE = 'Asia/Shanghai'
LANGUAGE_CODE = 'zh-cn'
cat /etc/sysconfig/clock
ZONE="Asia/Shanghai"
 
啟動服務:
cd /data/www/web/
python manage.py runserver 0.0.0.0:8880
 
 
 
 
django目錄結構
項目-》應用
項目文件夾里面可以包含多個應用,跟visual studio里面的解決方案下面有多個application一樣,最好只創建一個應用,因為一個應用對應一個數據庫
 
添加應用
添加一個應用,記住,應用一定要創建在項目文件夾下
cd /data/www/web/
python manage.py startapp blog
或者:
django-admin.py startapp blog
 
[root@VM_centos web]# ll
total 12
drwxr-xr-x 2 root root 4096 Feb 11 21:00 blog
-rwxr-xr-x 1 root root  246 Feb 11 10:56 manage.py
drwxr-xr-x 2 root root 4096 Feb 11 11:14 web
在項目文件夾里的setting.py
cd /data/www/web/
1. 添加應用:setting.py
INSTALLED_APPS = (
'blog',
2.修改url配置文件urls.py:用戶請求的url轉給誰去處理
url(r'^blog/index/$', 'blog.views.index'),
blog:blog目錄
views:blog目錄下的views.py
index:寫在views.py 里面的index函數
3.修改應用視圖文件:讓views.py文件的index方法來處理此請求:
cd  /data/www/web/blog/
vim views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse('<h1>hello django</h1>')
# Create your views here.

訪問:http://192.168.10.2:8880/blog/index
 
 
 


 
 
導入模板
cd /data/www/web
mkdir blog/templates
templates:名字不能改
cd blog/templates
vim index.html
<h1> hello </h1>
cd /data/www/web/blog/
vim views.py
修改視圖文件views.py
from django.template import loader, Context
1. 創建模板對象,把對應的模板文件導入,自動在templates目錄下找到index.html文件
loader.get_template('index.html')
2. 生成Context對象, 空的字典
c = Context({})
3. return HttpResponse(t.render(c))
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader, Context
# Create your views here.
def index(request):
t = loader.get_template('index.html')
c = Context({})
return HttpResponse(t.render(c))
 


定義數據模型
Django定義數據模型在App中的models.py文件,數據庫的表名稱以類的形式來定義:
vim models.py
from django.db import models
# Create your models here.
class Host(models.Model):
hostname
= models.CharField(max_length=50)
ipaddr
= models.IPAddressField()
def __unicode__(self):
return self.hostname

python manage.py validate //查看models.py的語法和邏輯是否正確,返回0 errors found正確
管理數據
python manage.py validate
初始化模型到數據庫,每個應用對應一個數據庫,每個數據庫都有下面的權限表:
sqlite> .tables
auth_group
auth_user_user_permissions
auth_group_permissions
blog_host
auth_permission
django_admin_log
auth_user
django_content_type
auth_user_groups
django_session
python manage.py syncdb
執行的時候會提示輸入django管理界面的用戶名和密碼(也就是django自帶的管理平臺的用戶名和密碼http://192.168.6.3:8880/admin,這個用戶名密碼會保存到auth_user表里)
打開django管理界面
http://192.168.10.2:8880/admin
確保數據庫引擎已經設置好
vim settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
執行python manage.py syncdb之后會生成db.sqlite3文件
[root@VM_centos web]# ll
total 48
drwxr-xr-x 2 root root 4096 Feb 13 13:55 blog
-rw-r--r-- 1 root root 34816 Feb 13 14:04 db.sqlite3
-rwxr-xr-x 1 root root 246 Feb 11 10:56 manage.py
drwxr-xr-x 2 root root 4096 Feb 13 14:01 web
 
換數據庫
https://docs.djangoproject.com/en/1.10/ref/settings/
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'cmdb',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
需要安裝python的mysql驅動
yum install -y MySQL-python.x86_64
 
 
 
通過admin頁面管理數據:
cd /data/www/web/blog
vim vim admin.py
把表在admin.py里注冊,admin才能識別
from django.contrib import admin
from blog.models import Host
或
from blog.models import * 導入所有的類
# Register your models here.

如果要顯示列,需要定義list_display列表:
class HostAdmin(admin.ModelAdmin):
list_display
= ['hostname','ipaddr']
admin.site.register(Host, HostAdmin)

 
 


訪問數據庫
 
訪問數據庫(一)
如何訪問數據,交互式方法:
python manage.py shell
from blog.models import Host //導入表
顯示數據:
node = Host.objects.all()
node.values()
增加數據:
n1 = Host(hostname=‘node1',ipaddr=‘1.1.1.1')
或:
n1 = Host()
n1.hostname = ‘node1’
n1.ipaddr = ‘1.1.1.1’
n1.save() //寫到表里
訪問數據庫(二)
通過視圖文件views.py來訪問數據
1.在urls.py文件里定義urls訪問路徑
vim urls.py
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'web.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/index/$', 'blog.views.index'),
url(r'^db/$', 'blog.views.db'),
)
2. 在views.py里定義訪問方法
vim views.py
from django.template import loader,Context
from blog.models import Host
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse('<h1>hello django</h1>')
def db(req):
h=Host()
h.hostname='test'
h.ip='192.168.2.3'
h.save()
return HttpResponse('OK')
 
request,req:表示客戶端向服務器端的請求,HttpRequest對象
訪問數據庫(三)
定義API
1. urls.py 定義訪問路徑
2. views.py 定義訪問方法 (API)
def collect(request):
if request.POST: 或 request.method == 'POST'
hostname = request.POST.get('hostname')
ipaddr = request.POST.get('ipaddr')
host = Host()
host.hostname = hostname
host.ipaddr = ipaddr
host.save()
return HttpResponse('OK')
else:
return HttpResponse('not data')
注釋掉csrf,讓django識別curl
vim settings.py
MIDDLEWARE_CLASSES = (
'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',
)
curl -d hostname='node05' -d ip='192.168.10.2' http://192.168.1.5:8000/db/


GET和POST方法
HttpRequest
request.POST.get('hostname')
或:
request.POST['hostname']
request.GET.get('hostname')
或:
request.GET['hostname']
傳遞數據
POST方法:
curl -d hostname='node12' -d ipaddr='12.12.12.12' http://192.168.3.72:8000/blog.collect/
GET方法:通過瀏覽器傳遞數據
http://192.168.3.72:8000/blog.get?hostname=n3&ipaddr=1.1.1.3
 
 
 


 
SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊
創建一個應用:
python manage.py startapp hostinfo
修改settings.py添加應用
 
 
admin.py
注冊數據庫:admin.py
from hostinfo.models import Host
class HostAdmin(admin.ModelAdmin):
list_display = ['hostname',
'vendor',
'product',
'osver',
'cpu_model',
'cpu_num',
'memory',
'sn']
admin.site.register(Host, HostAdmin)
 
syncdb
同步數據庫
定義url訪問路徑
views.py定義訪問方法
 
導入數據:
# cat data.sh
curl -d vendor='HP' -d product='2014' -d osver='rhel6.4' -d memory=4 -d cpu_model='Intel' -d cpu_num=8 -d sn='XXXXX' -d hostname='node2' http://192.168.131.10:8000/api/collect/
# bash data.sh
 
urllib,urllib2,httplib
使用urllib訪問網頁和傳數據,通常urllib,urllib2這兩個模塊一起添加
req = urllib2.urlopen('http://192.168.131.10:8000/api/collect')
對字典data進行編碼,生成post格式的數據
data ={'hostname':'node05','ip':'192.18.2.3'}
d = urllib.urlencode(data)
req = urllib2.urlopen('http://192.168.131.10:8000/api/collect/',d)
req.read()
vim models.py
from django.db import models
# Create your models here.
class Host(models.Model):
hostname = models.CharField(max_length=50)
ip = models.IPAddressField()
vendor = models.CharField(max_length=50)
product = models.CharField(max_length=50)
sn = models.CharField(max_length=50)
cpu_model = models.CharField(max_length=50)
cpu_num = models.IntegerField()
memory = models.CharField(max_length=50)
osver = models.CharField(max_length=50)
def __unicode__(self):
return self.hostname
class HostGroup(models.Model):
groupname = models.CharField(max_length=50)
members = models.ManyToManyField(Host)
創建HostGroup表,models.py
class HostGroup(models.Model):
groupname = models.CharField(max_length=50)
members = models.ManyToManyField(Host) # 多對多關系
注冊數據庫,admin.py
from hostinfo.models import HostGroup
class HostGroupAdmin(admin.ModelAdmin):
list_display = ['groupname']
admin.site.register(HostGroup, HostGroupAdmin)
 
 
python manage.py sqlall blog
BEGIN;
CREATE TABLE "blog_host" (
"id" integer NOT NULL PRIMARY KEY,
"hostname" varchar(50) NOT NULL,
"ip" char(15) NOT NULL,
"vendor" varchar(50) NOT NULL,
"product" varchar(50) NOT NULL,
"sn" varchar(50) NOT NULL,
"cpu_model" varchar(50) NOT NULL,
"cpu_num" integer NOT NULL,
"memory" varchar(50) NOT NULL,
"osver" varchar(50) NOT NULL
)
;
CREATE TABLE "blog_hostgroup_members" (
"id" integer NOT NULL PRIMARY KEY,
"hostgroup_id" integer NOT NULL,
"host_id" integer NOT NULL REFERENCES "blog_host" ("id"),
UNIQUE ("hostgroup_id", "host_id")
)
;
CREATE TABLE "blog_hostgroup" (
"id" integer NOT NULL PRIMARY KEY,
"groupname" varchar(50) NOT NULL
)
;
CREATE INDEX "blog_hostgroup_members_521bb4b0" ON "blog_hostgroup_members" ("hostgroup_id");
CREATE INDEX "blog_hostgroup_members_27f00f5d" ON "blog_hostgroup_members" ("host_id");
COMMIT;
 


django和web服務器整合  wsgi模塊   gunicorn模塊
wsgi模塊
wsgi:web server gateway interface web服務器網關接口
Django與Apache整合
安裝
yum install -y mod_wsgi
cd /etc/httpd/conf.d
vim wsgi.conf
 
 
 
 
gunicorn模塊
yum install -y epel-release
Django與nginx整合
netstat -tulanp|grep :8000
使用這個命令來看8000端口是否開啟,192.168.0.110上的8000是nginx開的,127.0.0.1上的8000是python這個進程開的。
所以使用netstat -tulanp|grep nginx這個命令是看不到的。
 
 
 


manage.py的用法
 
python manage.py runserver 8080
更改服務器端口號
python manage.py shell
啟動交互界面,如果系統安裝了ipython則啟動ipython,否則啟動python命令行,而且多了一些環境變量
python manage.py startapp books
創建一個app,名為books
python manage.py validate
驗證Django數據模型代碼是否有錯誤,models.py文件里面的代碼是否有誤
python manage.py sqlall books
為模型產生sql代碼,但不實際執行
python manage.py syncdb
運行sql語句,在數據庫里創建模型相應的Table
python manage.py dbshell
啟動數據庫的命令行工具

 


 
sqlite常用操作
 
跟mysql一樣,以分號 ; 作為一個語句的結束
sqlite> .tables
auth_group auth_user_user_permissions
auth_group_permissions blog_host
auth_permission django_admin_log
auth_user django_content_type
auth_user_groups django_session
sqlite
> .database
seq name file
--- --------------- ----------------------------------------------------------
0 main
/data/www/web/db.sqlite3
1 temp

sqlite
> .exit
[root@VM_centos web]
#

sqlite
>
.schema
CREATE TABLE
"auth_group" (
"id" integer NOT NULL PRIMARY KEY,
"name" varchar(80) NOT NULL UNIQUE
);
CREATE INDEX
"django_admin_log_6340c63c" ON "django_admin_log" ("user_id");
CREATE INDEX
"django_session_b7b81f0c" ON "django_session" ("expire_date");
sqlite
> .show
echo: off
explain: off
headers: off
mode: list
nullvalue:
""
output: stdout
separator:
"|"
width:
sqlite
> .help
.backup ?DB? FILE Backup DB (default
"main") to FILE
.bail ON
|OFF Stop after hitting an error. Default OFF
.databases List names
and files of attached databases
.dump ?TABLE? ... Dump the database
in an SQL text format
If TABLE specified, only dump tables matching
LIKE pattern TABLE.
.echo ON
|OFF Turn command echo on or off
.exit Exit this program
.explain ON
|OFF Turn output mode suitable for EXPLAIN on or off.
.genfkey ?OPTIONS? Options are:
--no-drop: Do not drop old fkey triggers.
--ignore-errors: Ignore tables with fkey errors
--exec: Execute generated SQL immediately
See file tool
/genfkey.README in the source
distribution
for further information.
.header(s) ON
|OFF Turn display of headers on or off
.help Show this message
.
import FILE TABLE Import data from FILE into TABLE
.indices ?TABLE? Show names of all indices
If TABLE specified, only show indices
for tables
matching LIKE pattern TABLE.
.load FILE ?ENTRY? Load an extension library
.mode MODE ?TABLE? Set output mode where MODE
is one of:
csv Comma
-separated values
column Left
-aligned columns. (See .width)
html HTML
<table> code
insert SQL insert statements
for TABLE
line One value per line
list Values delimited by .separator string
tabs Tab
-separated values
tcl TCL list elements
.nullvalue STRING Print STRING
in place of NULL values
.output FILENAME Send output to FILENAME
.output stdout Send output to the screen
.prompt MAIN CONTINUE Replace the standard prompts
.quit Exit this program
.read FILENAME Execute SQL
in FILENAME
.restore ?DB? FILE Restore content of DB (default
"main") from FILE
.schema ?TABLE? Show the CREATE statements
If TABLE specified, only show tables matching
LIKE pattern TABLE.
.separator STRING Change separator used by output mode
and .import
.show Show the current values
for various settings
.tables ?TABLE? List names of tables
If TABLE specified, only list tables matching
LIKE pattern TABLE.
.timeout MS Try opening locked tables
for MS milliseconds
.width NUM NUM ... Set column widths
for "column" mode
.timer ON
|OFF Turn the CPU timer measurement on or off

 


 
django中的模型三種關系
 
1=>N | 1<=>1 | N<=>N 三種關系
1對多:ForeignKey
1對1:OneToOneField
多對多:ManyToManyField
class Student(models.Model):
student_name = models.CharField(verbose_name=u'student name', max_length=100)
school = models.ForeignKey(School, on_delete=models.CASCADE, verbose_name='student school')
teachers = models.ManyToManyField(Teacher, verbose_name='students teachers')
bed = models.OneToOneField(Bed, on_delete=models.CASCADE, verbose_name='student bed')
 
 
 
 
django女孩博客
http://blog.djangogirls.org/
(繼續閱讀...)
文章標籤

AutoPoster 發表在 痞客邦 留言(0) 人氣(54)

  • 個人分類:生活學習
▲top
  • 3月 09 週四 201720:32
  • Python第十四天 序列化 pickle模塊 cPickle模塊 JSON模塊 API的兩種格式


文章出處
Python第十四天 序列化  pickle模塊  cPickle模塊  JSON模塊  API的兩種格式
 
目錄
Pycharm使用技巧(轉載)
Python第一天 安裝 shell 文件
Python第二天 變量 運算符與表達式 input()與raw_input()區別 字符編碼
Python第三天 序列 數據類型 數值 字符串 列表 元組 字典
Python第四天 流程控制 ifelse條件判斷 forwhile循環
Python第五天 文件訪問 for循環訪問文件 while循環訪問文件 字符串的startswith函數和split函數
Python第六天 類型轉換
Python第七天 函數 函數參數 函數變量 函數返回值 多類型傳值 冗余參數 函數遞歸調用 匿名函數 內置函數 列表表達式/列表重寫
Python第八天 模塊 包 全局變量和內置變量__name__ Python path
Python第九天 面向對象 類定義 類的屬性 類的方法 內部類 垃圾回收機制 類的繼承
Python第十天 print >> f,和fd.write()的區別 stdout的buffer 標準輸入 標準輸出 標準錯誤 重定向
Python第十一天 異常處理 glob模塊和shlex模塊 打開外部程序和subprocess模塊 subprocess類 Pipe管道 operator模塊 sorted函數 生成器 walk模塊 hashlib模塊
Python第十二天   收集主機信息   正則表達式   正則表達式  無名分組   有名分組
Python第十三天   django 1.6   導入模板   定義數據模型   訪問數據庫   GET和POST方法    SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊  django和web服務器整合  wsgi模塊   gunicorn模塊
Python第十四天 序列化  pickle模塊  cPickle模塊  JSON模塊  API的兩種格式
 
 
 
python中的任何數據類型都可以dump成json格式
 
簡單序列化
序列化
將對象的狀態信息轉換為可以存儲或傳輸的形式的過程
內存里面有一個數據結構,你希望把它保存下來重用,或者發送給其他人。
很多游戲允許你在退出的時候保存進度,然后你再次啟動的時候回到上次退出的地方
 
常用的一些序列化
pickle、cPickle
JSON
Shelve
YAML
 
-----------------------------------------------------------------------------------------
pickle模塊
所有python支持的類型都可以用pickle做序列化
終端一:
>>> entry = {'a':11, 'b':22}
>>> import pickle
>>> with open('entry.pickle', 'wb') as f:
... pickle.dump(entry, f)
從磁盤反序列化對象
終端二
>>> import pickle
>>> with open('entry.pickle', 'rb') as f:
... entry = pickle.load(f)
>>> entry
{'a': 11, 'b': 22}
 
序列化到內存
>>> b = pickle.dumps(entry)
>>> entry3 = pickle.loads(b)
 
----------------------------------------------------------------------
json模塊
序列化對象供其他語言讀寫
JavaScript Object Notation
Json是被設計為跨語言使用的
Json是文本格式
Json必須使用unicode編碼,默認utf-8方式存儲
 
 
數據保存至JSON文件
import json
序列化
d = {}
d['a'] = 'a'
d['b'] = 235
d['c'] = ('c1','c2')
d['d'] = True
d['e'] = None
with open('/tmp/d.json', mode='w') as fd:
json.dump(d, fd)
cat /tmp/d.json
反序列化
with open('/tmp/d.json') as fd:
d1 = json.load(fd)
json序列化
json.dump()
json.load()
json.dumps()
json.loads()
 
 
 
傳遞json格式的數據
定義url和方法
def collectjson(req):
if req.POST:
jsonobj = json.loads(req.body)
host = Host()
host.hostname = jsonobj['hostname']
host.vendor = jsonobj['vendor']
host.product = jsonobj['product']
……
host.save()
 
命令行訪問數據庫
python manager.py shell
from hostinfo.models import *
hg = HostGroup.objects.all()[0]
hg.groupname
hg.members.all()
h = hg.members.all()[0]
ip = h.ip
host = Host.object.get(hostname=‘agent03’)
host.ip = ‘192.168.1.113’ //修改記錄
host.save()
 
--------------------------------------------------------------------
API的兩種格式
----json 格式
{groupname: "web",members:[]}
[
{ groupanme: ‘web’,
members: [
{ hostname: ‘agent01’,
ip: ‘192.168.1.1’ },
]
},
]
----shell 格式
組名 主機名 ip地址
web agent02 192.168.3.163
web agent01 192.168.3.164
vim views.py
from django.shortcuts import render
from django.http import HttpResponse
from hostinfo.models import Host,HostGroup
import pickle
import json
# Create your views here.
def collect(req):
if req.POST:
#obj = pickle.loads(req.body)
obj = json.loads(req.body)
hostname = obj['hostname']
ip = obj['ip']
osver = obj['osver']
vendor = obj['vendor']
product = obj['product']
cpu_model = obj['cpu_model']
cpu_num = obj['cpu_num']
memory = obj['memory']
sn = obj['sn']
try:
host = Host.objects.get(sn=sn)
except:
host = Host()
host.hostname = hostname
host.ip = ip
host.osver = osver
host.vendor = vendor
host.product = product
host.cpu_model = cpu_model
host.cpu_num = cpu_num
host.memory = memory
host.sn = sn
host.save()
return HttpResponse('OK')
else:
return HttpResponse('not data')
def getjson(req):
ret_list = []
hg = HostGroup.objects.all()
for g in hg:
ret = {'groupname':g.groupname,'members':[]}
for h in g.members.all():
ret_h = {'hostname':h.hostname,'ip':h.ip}
ret['members'].append(ret_h)
ret_list.append(ret)
return HttpResponse(json.dumps(ret_list))
def gettxt(req):
res = ''
hg = HostGroup.objects.all()
for g in hg:
groupname = g.groupname
for h in g.members.all():
hostname = h.hostname
ip = h.ip
res += groupname+' '+hostname+' '+ip+'\n'
return HttpResponse(res)
json.dumps(ret_list)返回的是值是字符串類型
d1 = json.load(fd)
type(d1)
 
(繼續閱讀...)
文章標籤

AutoPoster 發表在 痞客邦 留言(0) 人氣(19)

  • 個人分類:生活學習
▲top
  • 3月 09 週四 201720:32
  • Python第十五天


文章出處
Python第十五天 
 
 
 
 
datetime模塊 time模塊
now = datetime.datetime.now() # 獲取當前時間
delta = datetime.timedelta(minutes=5) # 獲取前5分鐘時間
fiveminago = now – delta # 時間差
now > fiveminago # 時間比較
GMT_FORMAT = '%b %d %H:%M:%S GMT'
now.strftime(GMT_FORMAT) # 格式化時間
now.strftime('%s') //返回時間戳
time.time() //同上
time.ctime()  #相當于datetime.datetime.now()
 
import datetime
import time
def parseLogTime(line):
now = datetime.datetime.now()
month,day,time = line.split()[:3]
hour,minute,second = [int(i) for i in time.split(':')]
logtime = datetime.datetime(now.year,MONTH[month],int(day),hour,minute,second)
return logtime
 


pymssql模塊
 
--------------------------------------------------------------
示例
# coding=utf-8
import pymssql
class MSSQLServer(object):
def __init__(self):
self.server_ip = '.'
self.port = 1433
self.user_name = ''
self.user_psw = ''
self.database_name = ''
self.charset = 'utf8'
def get_connection(self):
conn = pymssql.connect(host=self.server_ip,
user=self.user_name,
password=self.user_psw,
database=self.database_name,
port=self.port,
charset=self.charset)
return conn
def mssql_query(self, sql_script, sql_param=None):
try:
conn = self.get_connection()
cursor = conn.cursor(as_dict=True)
if sql_param != '':
cursor.execute(sql_script, sql_param)
else:
cursor.execute(sql_script)
exec_result = cursor.fetchall()
cursor.close()
conn.close()
return exec_result
except Exception as ex:
cursor.close()
conn.close()
raise Exception(str(ex))
def mssql_exec(self, sql_script, sql_param=None):
try:
conn = self.get_connection()
cursor = conn.cursor(as_dict=True)
if sql_param is not None:
cursor.execute(sql_script, sql_param)
else:
cursor.execute(sql_script)
affect_rows = cursor.rowcount
conn.commit()
cursor.close()
conn.close()
return affect_rows
except Exception as ex:
cursor.close()
conn.rollback()
raise Exception(str(ex))
def mssql_test():
mssql_server = MSSQLServer()
mssql_server.server_ip = "."
mssql_server.port = 1433
mssql_server.charset = "utf8"
mssql_server.user_name = "gaowenjia"
mssql_server.user_psw = "ABC"
mssql_server.database_name = "Test_Sub"
sql_script = u"INSERT INTO [dbo].[TB_Lock]([C2]) VALUES('Test你好N')".encode("utf8")
exec_result = mssql_server.mssql_exec(sql_script=sql_script)
print("影響行數:{0}".format(exec_result))
sql_script = u"SELECT [ID],[C1],[C2] FROM [dbo].[TB_Lock]".encode("utf8")
query_result = mssql_server.mssql_query(sql_script=sql_script)
for row in query_result:
print("*" * 50)
id, c1, c2 = row["ID"], row["C1"], row["C2"]
print("id:{0}".format(id))
if c1 is None:
print("c1:{0}".format(c1))
else:
print("c1:{0}".format(c1.encode("utf8")))
if c2 is None:
print("c2:{0}".format(c2))
else:
print("c2:{0}".format(c2.encode("utf8")))
if __name__ == '__main__':
mssql_test()
--------------------------------------------------------------
Windows上安裝pymssql
Setp1:安裝python 2.7,
Setp2:安裝pymssql-2.0.0b1.win-amd64-py2.7
Setp3:將_mssql.pyd 復制粘貼到C:\Python27\Lib\site-packages 和 C:\Python27\DLLs\
Setp1:運行import pymssql;進行測試
參考鏈接:
http://blog.sina.com.cn/s/blog_83dc494d0101g8u5.html
https://pypi.python.org/pypi/pymssql/2.1.0
http://pymssql.org/en/latest/pymssql_examples.html
 
--------------------------------------------------------------
Linux上安裝pymssql
Linux上安裝pymssql需要的包:
freetds(http://www.filewatcher.com/m/freetds-0.82.tar.gz.1596755-0.html)
setuptools(https://pypi.python.org/pypi/setuptools)
pymssql(https://pypi.python.org/pypi/pymssql/)
 
安裝步驟:
1. 安裝freetds0.82
yum install -y gcc  gcc-c++
yum install -y freetds*
yum install -y python-devel
或
tar zxvf freetds-0.82.tar.gz
cd freetds-0.82
./configure --prefix=/usr/local/freetds --with-tdsver=8.0 --enable-msdblib --enable-dbmfix --with-gnu-ld --enable-shared --enable-static
make && make install
echo "/usr/local/freetds/lib" >> /etc/ld.so.conf.d/freetds.conf
ldconfig -v
2. 安裝python包 setuptools3.5.1
pip install setuptools==3.5.1
或
tar zxvf setuptools-3.5.1.tar.gz
cd setuptools-3.5.1
python setup.py install
3. 安裝pymssql2.1.0
下載地址:https://pypi.python.org/pypi/pymssql/2.1.3#downloads
pip install pymssql==2.1.0
或
tar zxvf pymssql-2.1.0.tar.gz
cd pymssql-2.1.0
python setup.py install
=======================================
未安裝freetds會提示:
setup.py: Not using bundled FreeTDS
如果安裝freetds并配置/etc/ld.so.conf.d/freetds.conf,但未執行ldconfig -v,會報錯:
import pymssql
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: libsybdb.so.5: cannot open shared object file: No such file or directory
 


線程 thread
thread模塊
threading模塊
thread模塊是低級模塊
threading模塊是高級模塊
生產中要用threading模塊而不用thread模塊
GIL:Python無法高效的實現多線程的原因
線程的特點:多功能衣:1631114712
- 線程的生命周期
- 開始
- 運行
- 結束
線程的退出:
- 進程執行完成
- 線程的退出方法
- python系統退出
我們通常把當前進程叫做主線程或者主進程。
函數是通過thread.start_new_thread來調用的,說明它是在線程中運行的。
模塊函數
import thread,threading
start_new_thread(func, args)
func:函數名
args:元組
allocate_lock()
exit()
#!/usr/bin/env python
#encoding:utf8
import thread
import time
def func(name,i):
    for n in xrange(i):
        print name,n
        #time.sleep(1)
thread.start_new_thread(func, ('聲音',3))
thread.start_new_thread(func, ('畫面',3))
time.sleep(1)
LockType對象方法
acquire()
locked()
release()  //釋放鎖,使用前線程必須已獲得鎖定,否則將拋出異常
thread鎖使用
lock = thread.allocate_lock():生成全局鎖對象
lock.acquire():加鎖
線程使用鎖對象
lock.release():線程調度釋放鎖
查看locked()狀態
示例1
#!/usr/bin/env python
#encoding:utf8
import thread
import time
def func(name, i, l):
    for n in xrange(i):
        print name, n
        time.sleep(1)
    l.release()
    
lock = thread.allocate_lock()
lock.acquire()
thread.start_new_thread(func, ('聲音', 3, lock))
thread.start_new_thread(func, ('畫面', 3, lock))
while lock.locked():
    pass
print lock.locked()
print "Exit main process"
示例2
#!/usr/bin/env python
import thread
import time
def world():
    for i in range(5):
        if w_lock.acquire():
            print 'world', time.ctime()
            h_lock.release()
h_lock = thread.allocate_lock()
w_lock = thread.allocate_lock()
thread.start_new_thread(world, ())
w_lock.acquire()
for i in range(5):
    if h_lock.acquire():
        print 'hello',
        w_lock.release()
while h_lock.locked():
    pass
示例3
#!/usr/bin/env python
import thread
import time
def hello():
    for i in xrange(5):
        h_lock.acquire()
        print 'hello',
        w_lock.release()
def world():
    for i in xrange(5):
        w_lock.acquire()
        print 'world', time.ctime()
        h_lock.release()
    lock.release()
lock = thread.allocate_lock()  分配鎖
lock.acquire() 獲得鎖
h_lock = thread.allocate_lock()
w_lock = thread.allocate_lock()
w_lock.acquire()
thread.start_new_thread(hello, ())
thread.start_new_thread(world, ())
while lock.locked():  是否獲得鎖
    pass
threading模塊
threading不需要進程來控制線程,主進程會等待線程執行完畢才退出
threading.Thread:類
成員方法:
    - start()  //啟動線程 非阻塞
    - run()   //可以重寫
    - join()  //阻塞當前線程的執行
    - getName()
    - setName()
    - isDaemon()  //判斷線程是否隨主線程一起結束
    - setDaemon()  //設置線程與主線程一起結束
import time
import threading
def t1(name, x):
    for i in xrange(x):
        print i, name
        time.sleep(1)
th1 = threading.Thread(target=t1, args=('聲音', 3))
th2 = threading.Thread(target=t1, args=('畫面', 3))
target:函數名
args:函數的參數
th1.setDaemon(True)   //隨著主線程的退出而退出,一定要寫在th1.start()前面
th1.start()     //運行一個線程
#th1.run()     //一直運行這個線程,直到運行完才會運行下一個線程
#th1.join()    //等待線程終止
th2.start()
Lock對象
lock = threading.Lock()
lock. acquire()   //獲取鎖
lock.release()     //釋放鎖
lock.locked()     //查看鎖狀態
f
(繼續閱讀...)
文章標籤

AutoPoster 發表在 痞客邦 留言(0) 人氣(30)

  • 個人分類:生活學習
▲top
  • 3月 09 週四 201720:32
  • vmware里面的名詞 vSphere、vCenter Server、ESXI、vSphere Client


文章出處
vmware里面的名詞 vSphere、vCenter Server、ESXI、vSphere Client
 
vSphere、vCenter Server、ESXI、vSphere Client
VSphere包含很多產品組件,是vmware虛擬化的平臺
ESXI實際就是一個Linux操作系統,就是一個宿主機,用戶不是root,而是admin,并且需要服務器支持硬件虛擬化
多臺ESXI主機組成集群,多個集群組成一個數據中心,Vcenter既可以管理集群,也可以管理數據中心
vCenter Server 相當于微軟的system center virtual machine manager(scvmm)是一個統一化管理的工具
vSphere Client 和 vCenter Server 都可以管理 ESXi 服務器,前者只是一個客戶端只能管理一臺機器,后者是集中管理整個集群和數據中心
VSphere client 虛擬機主機管理客戶端,Vcenter是一個強大的管理端,它可以將多臺ESXI主機作為集群,Vmotion等多個功能都必須使用Vcenter才能實現。
連接原理如下
VSphere---->Vcenter------>Esxi Server
就是,VSphere去連接Vcenter,通過Vcenter管理ESXI主機。
 
 
RHEV:redhat enterprise  virtualization 紅帽企業虛擬化
oVirt:是RHEV的開源版本,open Virtmanager,kvm虛擬化管理平臺面向小型企業
 
 
vCenter Server類似的產品:citrix里的xencenter,oVirt里的oVirt-engine,微軟的scvmm(system center virtual machine manager)
ESXI類似的產品:citrix里的xenserver,oVirt里的oVirt Node,微軟的Hyper-v(嚴格來說Hyper-v跟ESXI、oVirt Node不是同一個級別,ESXI本身就是一個Linux操作系統
,而Hyper-v只是Windows Server里面的一個組件)
 
(繼續閱讀...)
文章標籤

AutoPoster 發表在 痞客邦 留言(0) 人氣(75)

  • 個人分類:生活學習
▲top
  • 3月 09 週四 201720:32
  • Windows2012R2 NTP時間同步


文章出處
Windows2012R2 NTP時間同步
Windows2012R2里沒有了internet時間,需要使用另外的方式去做時間同步
 
 
 
 
 
下面分兩個情況
兩個情況,兩個情況都需要用修改組策略的方式來做
 
 
 
情況一
沒有Windows域環境
集群中的每個服務器都要能上網,每個服務器都要執行下面的操作
開啟 NTP Client 服務
1、打開 powershell 終端, 輸入:gpedit.msc,打開組策略管理器
2、執行上述命令后,計算機策略對話框打開,按照如下路徑 計算機配置\管理模板\系統\windows 時間服務\時間提供程序 找到服務器設置文件
3、雙擊 配置 Windows NTP 客戶端,顯示 配置 Windows NTP 客戶端
4、將 Ntp Server項,輸入將要同步到的時間服務器IP地址(這里輸入阿里云的ntp服務器地址: time.pool.aliyun.com),注意 0x9 或 0x1 必須要有;在 類型 項, 選擇 NTP;點擊 應用、確定 按鈕;
 
5、啟動 NTP 客戶端;啟用NTP客戶端;點擊 應用、確定 按鈕;
 
 
 
6、執行下面命令更新組策略
gpupdate /force
 
7、檢查W32Time服務是否啟動,啟動類型是否是  自動啟動
 
 
(1)服務器不能上網,當前環境有ntpd服務器
在第4步里把ntp server的地址改為內網ntpd服務器的地址即可
(2)服務器必須要能上網,使用公網上的ntpd服務器,例如阿里云的ntpd服務器
 
 
情況二
有Windows域環境
只需要對域控制器執行操作,其他域里面的client都不需要動
更改方法跟情況一的一樣,修改組策略-》更新組策略-》檢查W32Time服務是否啟動
如果對client設置了組策略,那么client會用組策略的配置,而不是跟域控制器同步時間
 
 
 
注意點:Windows是使用ntpd命令的方式跟NTP服務器同步時間,也就是當client和server的時間相差太大的時候,client無法與server進行時間同步
也就是,無論是有域環境還是沒有域環境,無論是用組策略還是不用組策略都是這樣
這個跟Linux的ntpdate命令 ntpd命令相同,Linux的ntpdate命令無論client與server時間相差多大都可以跟server同步,而ntpd命令當時間相差太大則無法同步
 
網上還有另一種方法不用修改組策略,但是本人還沒試過
有Windows域環境,在每臺client里添加一個任務計劃,定時執行下面命令
w32tm /config /syncfromflags:manual /manualpeerlist:time.stdtime.gov.tw
w32tm
/config /update

 
沒有Windows域環境,在每臺client里添加一個任務計劃,定時執行下面命令
 
 
參考文章
https://social.technet.microsoft.com/Forums/zh-TW/8543dc5d-703c-4b49-a60f-683e76e09f09/windows-2012-ad-client?forum=winserver2012zhtw
http://blog.csdn.net/hobbithero/article/details/53349531


 
內網和公共NTP服務器
https://help.aliyun.com/knowledge_detail/40583.html
更新時間:2016-07-12 15:23:55
內網NTP服務器
阿里云為云服務器ECS提供了內部的NTP時間服務器,如下:
10.143.33.50
10.143.33.51
10.143.33.49
10.143.0.44
10.143.0.45
10.143.0.46
公共NTP服務器
雖然非阿里云的設備不能用阿里云的內網NTP服務器,但是阿里云提供了公共NTP服務器,供互聯網上的設備使用。其主要特性是GPS、北斗授時、原子鐘守時的一級時間源多機房、多鏈路冗余。
服務域名是:
Unix類系統:time1-7.aliyun.com ,time1.aliyun.com,time2.aliyun.com,time3.aliyun.com。。。。。。
Windows: time.pool.aliyun.com
另外,阿里云還提供了其他的互聯網基礎服務,例如:
公共DNS:223.5.5.5/223.6.6.6,域名是 http://www.alidns.com
公共鏡像站:http://mirrors.aliyun.com/ 鏡像同步頻率是每天凌晨2:00-4:00,覆蓋了大多數開源軟件及Linux發行版。
(繼續閱讀...)
文章標籤

AutoPoster 發表在 痞客邦 留言(0) 人氣(37)

  • 個人分類:生活學習
▲top
  • 3月 09 週四 201720:32
  • Python第一天 安裝 shell 文件


文章出處
Python第一天  安裝  shell  文件
 
目錄
Pycharm使用技巧(轉載)
Python第一天 安裝 shell 文件
Python第二天 變量 運算符與表達式 input()與raw_input()區別 字符編碼
Python第三天 序列 數據類型 數值 字符串 列表 元組 字典
Python第四天 流程控制 ifelse條件判斷 forwhile循環
Python第五天 文件訪問 for循環訪問文件 while循環訪問文件 字符串的startswith函數和split函數
Python第六天 類型轉換
Python第七天 函數 函數參數 函數變量 函數返回值 多類型傳值 冗余參數 函數遞歸調用 匿名函數 內置函數 列表表達式/列表重寫
Python第八天 模塊 包 全局變量和內置變量__name__ Python path
Python第九天 面向對象 類定義 類的屬性 類的方法 內部類 垃圾回收機制 類的繼承
Python第十天 print >> f,和fd.write()的區別 stdout的buffer 標準輸入 標準輸出 標準錯誤 重定向
Python第十一天 異常處理 glob模塊和shlex模塊 打開外部程序和subprocess模塊 subprocess類 Pipe管道 operator模塊 sorted函數 生成器 walk模塊 hashlib模塊
Python第十二天   收集主機信息   正則表達式   正則表達式  無名分組   有名分組
Python第十三天   django 1.6   導入模板   定義數據模型   訪問數據庫   GET和POST方法    SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊  django和web服務器整合  wsgi模塊   gunicorn模塊
Python第十四天 序列化  pickle模塊  cPickle模塊  JSON模塊  API的兩種格式
 
 
python里面一切都是對象 object
代碼縮進:建議用四個空格來縮進,不要用tab鍵
凡是語法的,后面都有冒號,比如循環語句、條件語句、定義函數、定義類、異常處理、with打開文件等
 
為什么 print("hello word!") 必須加括號才可以 
python 3.x print需要括號,python 2.x 不需要
 
安裝
 
Linux自帶python,windows需要下載msi文件進行安裝,還要指定環境變量
#查看python版本和當前安裝的python版本
python -V
rpm -qa|grep python
python-2.6.6-52.el6.x86_64


python shell
解釋器交互
python shell
ipython(需要安裝第三方模塊ipython包,ipython包沒有源碼包)
python軟件包安裝方式,pip,pip能解決模塊依賴關系,pip安裝器不需要像yum那樣配置yum源,搜索位置https://pypi.python.org/pypi/
pip網上搜索位置
https://pypi.python.org/pypi/
安裝python包
先安裝epel源
yum install -y epel-release
yum makecache
yum install -y python-pip
列出python包
pip list
安裝python包
pip install ipython
指定版本號
pip install ipython==1.2.1
第三方python模塊安裝包路徑
/usr/lib/python2.6/site-packages/
/usr/lib64/python2.6/site-packages/
 
卸載python包
刪除指定的模塊或者包
pip uninstall ipython
 
[root@gz3 ~]# ipython
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37)
Type "copyright", "credits" or "license" for more information.
IPython 1.2.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]:
 
 


python文件
 
執行
bash文件
vi 1.sh
#!/bin/bash
echo 'hello'
sh 1.sh
chmod +x 1.sh
./1.sh
python文件
vi 1.py
#!/usr/bin/python
print 'hello'
python 1.py
chmod +x 1.py
./1.py
 
python文件類型
(1)py
python源碼文件
(2)pyc
Python源碼文件經編譯后生成的擴展名為”pyc”的文件
編譯方法:
import py_compile
py_compile.compile('python源碼文件絕對或相對路徑')
(3)pyo
優化代碼
也是經過編譯的,但是優化過的源碼文件,擴展名為”pyo”
python –O –m py_compile hello.py
 
(繼續閱讀...)
文章標籤

AutoPoster 發表在 痞客邦 留言(0) 人氣(6)

  • 個人分類:生活學習
▲top
  • 3月 09 週四 201720:32
  • Python第二天 變量 運算符與表達式 input()與raw_input()區別 字符編碼 python轉義符 字符串格式化


文章出處
Python第二天  變量  運算符與表達式  input()與raw_input()區別  字符編碼  python轉義符  字符串格式化
 
 
 
目錄
Pycharm使用技巧(轉載)
Python第一天 安裝 shell 文件
Python第二天 變量 運算符與表達式 input()與raw_input()區別 字符編碼
Python第三天 序列 數據類型 數值 字符串 列表 元組 字典
Python第四天 流程控制 ifelse條件判斷 forwhile循環
Python第五天 文件訪問 for循環訪問文件 while循環訪問文件 字符串的startswith函數和split函數
Python第六天 類型轉換
Python第七天 函數 函數參數 函數變量 函數返回值 多類型傳值 冗余參數 函數遞歸調用 匿名函數 內置函數 列表表達式/列表重寫
Python第八天 模塊 包 全局變量和內置變量__name__ Python path
Python第九天 面向對象 類定義 類的屬性 類的方法 內部類 垃圾回收機制 類的繼承
Python第十天 print >> f,和fd.write()的區別 stdout的buffer 標準輸入 標準輸出 標準錯誤 重定向
Python第十一天 異常處理 glob模塊和shlex模塊 打開外部程序和subprocess模塊 subprocess類 Pipe管道 operator模塊 sorted函數 生成器 walk模塊 hashlib模塊
Python第十二天   收集主機信息   正則表達式   正則表達式  無名分組   有名分組
Python第十三天   django 1.6   導入模板   定義數據模型   訪問數據庫   GET和POST方法    SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊  django和web服務器整合  wsgi模塊   gunicorn模塊
Python第十四天 序列化  pickle模塊  cPickle模塊  JSON模塊  API的兩種格式
 
 
 
Python變量
變量的命名
- 變量名由字母、數字、下劃線組成。
- 變量不能以數字開頭
- 不可以使用關鍵字
- a a1 _a
變量的賦值
- 是變量的聲明和定義的過程,等號兩邊可以有空格,而bash等號兩邊不能有空格
a = 1
id(a)
變量不需要聲明,根據所賦值內容決定變量的數據類型
aa是整型
>>> aa=3
>>> aa
3
非數字要用引號括起來,否則會認為是變量
abc = ccc 報錯 NameError: name 'ccc' is not defined
ab = 'ddd' 正確
>>> ab = 'ddd'
>>> print ab
ddd


運算符與表達式
Python運算符包括
- 賦值運算符
=:x = 3, y = ‘abcd’
+=: x += 2
-=:x -= 2
*=:x *= 2
/=: x /= 2
%=:x %= 2
- 算術運算符
+
-
*
/   除法,有小數
//  整除,沒有小數
%
**   乘方 2**3=8 表示2的3次方
- 關系運算符
> :1 > 2
< :2 < 3
>=:1 >= 1
<=:2 <= 2
==:2 == 2
!=: 1 != 2
- 邏輯運算符
and邏輯與: True and False
or邏輯或: False or True
not邏輯非: not True
表達式是將不同的數據(包括變量、函數)用運算符號按一定規則連接起來的一種式子。
type函數
查看變量的數據類型
type(變量名)
help函數
查看幫助
help(名稱)
數字類型小于任何其他非數字類型,所以也小于字符串類型。
字符串之間的比較,從左到右,先比較第一個字符,如果第一個字符一樣,再比較第二字符,依次進行比較
那么字符之間比較的原則是根據ACSII,'a'的ASCII值是97,ord('a')是97,ord('A')是65,所以’a' > 'A'。
那么’4‘與’35'哪個大?


input()與raw_input()區別
input()與raw_input()返回值都是字符串
input() 輸入的內容不能是字符,否則會當成變量
raw_input()   輸入的內容不受限制
#!/usr/bin/python
#encoding:utf8
num1 = input("請輸入數字: ")
num2 = input("Please input a number: ")
print "%s + %s = %s" % (num1, num2, num1+num2)
print "%s - %s = %s" % (num1, num2, num1-num2)
print "%s * %s = %s" % (num1, num2, num1*num2)
print "%s / %s = %s" % (num1, num2, num1/num2)
print "%s " % num1
 
print "%.2f" % (int(free)/1024.0)+'M'
 
 
 
 
字符串格式化
%表示格式化字符串的格式符號。
%s,格式化字符串,字符,如果只有一個字符,通常不用括號,格式化之后變為字符串
%d,表示整數的字符串,格式化字符串,數字,如果只有一個字符,通常不用括號,格式化之后變為字符串
%x,表示16進制的字符串
%f,表示浮點數字符串,%.2f ,.2表示顯示幾位小數,如果只有一個字符,通常不用括號,格式化之后變為字符串,所以可以用+號連接'M'
示例
import sys
i
=10
sys.stdout.write(
"str:%d" %i)
import sys
i
='10'
sys.stdout.write(
"str:%s" %i)
import sys
i
=10
sys.stdout.write(
"str:%02f" %i)

 
 
 


python轉義符
python里面有兩種轉義符
1、字符串格式化里面的轉義符
2、正則表達式里面的轉義符
 
1、%,兩個特殊符號前面加%轉義(字符串格式化里面的轉義符)
sys.stdout.write("str:%d%%" %i)

 
 2、\ 轉義符  (正則表達式里面的轉義符)
轉義符和元字符跟shell的基本一樣,轉義都有\ 反斜杠
http://www.cnblogs.com/MYSQLZOUQI/p/5189884.html
python元字符:    .、^、$、*、+、?、{}、[]、\ 轉義、|、()
 
我們想讓通配符,或者元字符變成普通字符。那么這里我們就需要用到轉義符了。 shell提供轉義符有三種。 
'' 單引號,硬轉義,其內部所有的shell元字符、通配符都會被關掉。注意,硬轉義中不允許出現’(單引號)。
"" 雙引號,軟轉義,其內部只允許出現特定的shell元字符($,`,\):$用于變量值替換、`用于命令替換、\用于轉義單個字符
\ 反斜杠,轉義,去除其后緊跟的元字符或通配符的特殊意義。
http://www.2cto.com/os/201410/344020.html


 
 
#encoding:utf8:指定字符編碼支持中文
有幾種寫法
#encoding:utf8
#encoding:utf-8
#-*- encoding:utf-8 -*-
#coding:utf8
#coding:utf-8
#-*- coding:utf-8 -*-
 
(繼續閱讀...)
文章標籤

AutoPoster 發表在 痞客邦 留言(0) 人氣(1)

  • 個人分類:生活學習
▲top
  • 3月 09 週四 201720:32
  • Python第三天 序列 數據類型 數值 字符串 列表 元組 字典


文章出處
Python第三天 序列  數據類型  數值  字符串  列表  元組  字典
 
目錄
Pycharm使用技巧(轉載)
Python第一天 安裝 shell 文件
Python第二天 變量 運算符與表達式 input()與raw_input()區別 字符編碼
Python第三天 序列 數據類型 數值 字符串 列表 元組 字典
Python第四天 流程控制 ifelse條件判斷 forwhile循環
Python第五天 文件訪問 for循環訪問文件 while循環訪問文件 字符串的startswith函數和split函數
Python第六天 類型轉換
Python第七天 函數 函數參數 函數變量 函數返回值 多類型傳值 冗余參數 函數遞歸調用 匿名函數 內置函數 列表表達式/列表重寫
Python第八天 模塊 包 全局變量和內置變量__name__ Python path
Python第九天 面向對象 類定義 類的屬性 類的方法 內部類 垃圾回收機制 類的繼承
Python第十天 print >> f,和fd.write()的區別 stdout的buffer 標準輸入 標準輸出 標準錯誤 重定向
Python第十一天 異常處理 glob模塊和shlex模塊 打開外部程序和subprocess模塊 subprocess類 Pipe管道 operator模塊 sorted函數 生成器 walk模塊 hashlib模塊
Python第十二天   收集主機信息   正則表達式   正則表達式  無名分組   有名分組
Python第十三天   django 1.6   導入模板   定義數據模型   訪問數據庫   GET和POST方法    SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊  django和web服務器整合  wsgi模塊   gunicorn模塊
Python第十四天 序列化  pickle模塊  cPickle模塊  JSON模塊  API的兩種格式
 
 
 
 
數據類型
數值
字符串
列表
元組
字典
 
 
序列
序列:字符串、列表、元組
序列的兩個主要特點是索引操作符和切片操作符
- 索引操作符讓我們可以從序列中抓取一個特定項目
- 切片操作符讓我們能夠獲取序列的一個切片,即一部分序列
序列的基本操作
1. len(): 求序列的長度
2. +: 連接2個序列
3. *: 重復序列元素
4. in: 判斷元素是否在序列中
5. max(): 返回最大值
6. min(): 返回最小值
7. cmp(x, y):比較兩個序列是否相等 返回值大于0 ,等于0,小于0
cmp:按照字符串比較,字符串比較的原則就是一個字符一個字符的比較,字符按照ASCII碼來比較,字符1比字符2小,所以gene1001小于gene2。
 
------------------------------------------------------------
數值類型
- 整型  2^32個數字,范圍-2,147,483,648到2147483647
- 長整型  區分普通整型,需要在整數后加L或l。2345L,0x34al
- 浮點型  0.0,12.0,-18.8,3e+7
- 復數型  - 3.14j,8.32e-36j
-------------------------------------------------------------
字符串''類型
字符串是不可變數據類型
有三種方法定義字符串類型
str = 'this is a string'
str = "this is a string"
str = '''this is a string'''  或 """this is a string"""
三重引號(docstring)除了能定義字符串還可以用作注釋
python里面單引號和雙引號沒有任何區別
\n:換行
str = "this is a \nstring"
字符串索引
字符串是序列,可以通過索引取每個字符
加號 :字符串連接符
- str = 'abcde'
- str[0] + str[1]
字符串切片
str[start:end:step]
step:為負數表示從右向左
>>> str[1:3]
'bc'
>>> str[:3]
'abc'
>>> str[3:]
'de'
>>> str[::1]
'abcde'
>>> str[::2]
'ace'
>>> str[-1]
'e'
>>> str[-4:-1]
'bcd'
>>> str[-2:-4:-1]
'dc'
---------------------------------------------------
元組()類型
元組和列表十分相似
元組和字符串一樣是不可變的,不可變的意思是元組里面的元素不能修改,比如a[-1] = xx 會報錯
- 元組可以存儲一系列的值
- 元組通常用在用戶定義的函數能夠安全地采用一組值的時候,即被使用的元組的值不會改變。
創建元組
t= ()
t= (2,) 一定要加逗號才是元組,否則會當普通字符串對待
t = ('james', 'M')
t = ('james', 'M',(1,)) 元組里面包含元組
j = 'sd'
t = (j, 'M') 包含變量
print t
('sd', 'M')
print t[0] 返回第一個元素
 
元組操作
- 元組和字符串一樣屬于序列類型,可以通過索引和切片操作
- 元組值不可變
元組的拆分
t = (1,2,3)
a, b, c = t
a
1
b
2
c
3
 
---------------------------------------------------
列表[]類型
列表(list)是處理一組有序項目的數據結構,即可以在列表中存儲一個序列的項目。
列表是可變類型的數據類型
創建列表
list1 = []
list2 = list()   list()函數
list3 = ['a',1,2]
list4 = ['a',1,(1,),['sdf','sww]]
對某項目賦值,下標從0開始
list3[0] = 'b'
列表操作
- 取值
切片和索引
切片
l
= list(range(10))
l
[0,
1, 2, 3, 4, 5, 6, 7, 8, 9]
l[
5:0:-1] 輸出:[5, 4, 3, 2, 1]
l[
5:4:-1] 輸出:[5]
l[:
3:-1] 輸出:[9, 8, 7, 6, 5, 4]
l[0:
3:-1] 輸出:[]
l[
9::-1] 輸出:[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
l[
-2:]( l[-2:10:1]) 輸出:[8, 9]
l[
2:]( l[2:10:1]) 輸出:[2, 3, 4, 5, 6, 7, 8, 9]
l[:
-2]( l[0:-2:1]) 輸出:[0, 1, 2, 3, 4, 5, 6, 7]
l[0] 輸出:0
l[列表最小值:列表最大值:步進]
輸出不包含列表最大值
列表最小值下標從0開始
-1:9
-2:8

- 添加
list.append()
list1[2].append('abc')  如果列表里面又有列表使用下標來訪問
- 刪除
del list[x] 刪除某個元素  del list 刪除整個列表
list.remove(列表里面實際的值)
- 修改
list[] = x
- 查找
var in list
- 插入
list.insert(list[x],object)  在下標前插入一個對象
- 排序
list.sort()
- 反轉
list.reverse()
- 彈出
list.pop([index])  返回一個元素并刪除這個元素,參數是下標,沒有參數會刪除最后一個元素
- 擴展
list.extend()  可迭代的,相比append()方法可以追加多個值
---------------------------------------------------------
 
字典{}類型
字典是python中的唯一的映射類型(哈希表)
字典對象是可變的,但是字典的鍵必須使用不可變對象,一個字典中可以使用不同類型的鍵值。
跟redis的set類型一樣,字典里的key不能重復,賦值的時候如果發現已有key則替換
字典的方法:
- keys() 返回所有key
- values() 返回所有value
- items() 返回一個列表,key和value在一個元組里
創建字典
dic = {}
dic = dict()
dict()函數
help(dict)
dict((['a',1],['b',2]))
dict(a=1, b=2)
bb=dict(a=1, b=2)
bb
{
'a': 1, 'b': 2}

 
fromkeys()函數
fromkeys(S[,v]) S指定一個序列,v指定value的值,默認為None。
dic.fromkeys(range(3),100)
In [4]: dic.fromkeys(range(3),100)
Out[4]: {0: 100, 1: 100, 2: 100}
fromkeys函數創建的字段需要賦值到另一個字典才能保存
ddict = {}.fromkeys(('x','y'), 100)
 
訪問字典
直接使用key訪問:key不存在會報錯,可以使用has_key()或者in和not in判斷。
循環遍歷:
例:
for i in dic.keys():
for i in dic:
print i 讀取的是key
print dict1[i] 讀取的是value
for i, o in dic.items():
print i, o
 
#!/usr/bin/python
info = {}  創建一個空字典
name = raw_input("Please input name: ")
age = raw_input("Please input age: ")
gender = raw_input('Please input (M/F): ')
info['name'] = name
info['age'] = age
info['gender'] = gender
for k, v in info.items():
print "%s: %s" % (k, v)
print 'main end'
 
 
 
 
 
 
 
 
 
 
(繼續閱讀...)
文章標籤

AutoPoster 發表在 痞客邦 留言(0) 人氣(3)

  • 個人分類:生活學習
▲top
  • 3月 09 週四 201720:31
  • Python第四天 流程控制 if else條件判斷 for循環 while循環


文章出處
Python第四天   流程控制   if else條件判斷   for循環 while循環
 
 
目錄
Pycharm使用技巧(轉載)
Python第一天 安裝 shell 文件
Python第二天 變量 運算符與表達式 input()與raw_input()區別 字符編碼
Python第三天 序列 數據類型 數值 字符串 列表 元組 字典
Python第四天 流程控制 ifelse條件判斷 forwhile循環
Python第五天 文件訪問 for循環訪問文件 while循環訪問文件 字符串的startswith函數和split函數
Python第六天 類型轉換
Python第七天 函數 函數參數 函數變量 函數返回值 多類型傳值 冗余參數 函數遞歸調用 匿名函數 內置函數 列表表達式/列表重寫
Python第八天 模塊 包 全局變量和內置變量__name__ Python path
Python第九天 面向對象 類定義 類的屬性 類的方法 內部類 垃圾回收機制 類的繼承
Python第十天 print >> f,和fd.write()的區別 stdout的buffer 標準輸入 標準輸出 標準錯誤 重定向
Python第十一天 異常處理 glob模塊和shlex模塊 打開外部程序和subprocess模塊 subprocess類 Pipe管道 operator模塊 sorted函數 生成器 walk模塊 hashlib模塊
Python第十二天   收集主機信息   正則表達式   正則表達式  無名分組   有名分組
Python第十三天   django 1.6   導入模板   定義數據模型   訪問數據庫   GET和POST方法    SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊  django和web服務器整合  wsgi模塊   gunicorn模塊
Python第十四天 序列化  pickle模塊  cPickle模塊  JSON模塊  API的兩種格式
 
 
Python流程控制
函數,循環,if條件,類定義等后面有block,block要縮進,因此這些語句后面要加上冒號,這是python的語法
python的冒號和java、c中的{}是一樣的
block是一組語句
注:Python使用縮進作為其語句分組的方法,建議使用4個空格
#!/usr/bin/python
score = int(raw_input("Please a num: "))
if score >= 90:
print 'A'
print 'very good'
elif score >= 80:
print 'B'
print 'good'
elif score >= 70:
print 'C'
print 'pass'
else:
print 'D'
print 'End'
 


條件判斷
邏輯值(bool)包含了兩個值:
- True:表示非空的量(比如:string,tuple,list,set,dictonary),所有非零數。
- False:表示0,None,空的量等。
elif語句:
- if expression1:
statement1(s)
elif expression2:
statement2(s)
else:
statement2(s)
 
 
if else判斷例子
#!/usr/bin/python

score
= int(raw_input("Please a num: "))
if score >= 90:
print 'A'
print 'very good'
elif score >= 80:
print 'B'
print 'good'
elif score >= 70:
print 'C'
print 'pass'
else:
print 'D'
print 'End'
raw_input輸入是字符串,需要用int()函數進行轉換

 


循環
 
print 相當于Linux的echo命令
print  xx ,   加一個逗號不會換行,默認會換行
range函數 相當于Linux的seq 命令
range(start,stop,step)    倒序range(10,0,-1)
range可以快速的生成一個序列,返回是一個列表
range(I, j, [,步進值])
- 如果所創建對象為整數,可以用range
- i為初始值,不選默認為0
- j為終止值,但不包括在范圍內
- 步進值默認為1.
xrange
生成一個可迭代的對象
xrange(start,stop,step)-> xrange object
a = xrange(10)
for i in xrange(10): print i
for循環
for
else
for循環如果正常結束,才會執行else語句。
 
列表重寫法
#!/usr/bin/python
for i in [i**2 for i in range(1, 11) if i % 2 != 0]:
print i,
 
break
continue
pass:什么都不做,占位
exit():相當于shell里的exit命令,需要導入sys模塊
#!/usr/bin/python
import sys
import time
for i in xrange(10):
if i == 3:
continue
elif i == 5:
continue
elif i == 6:
pass
elif i == 7:
sys.exit()
print i
else:
print 'main end'
print "hahaha"
在ipython里導入模塊
In [9]: import random
In [10]: random.
random.BPF random.SystemRandom random.expovariate random.lognormvariate random.sample random.vonmisesvariate
random.LOG4 random.TWOPI random.gammavariate random.normalvariate random.seed random.weibullvariate
random.NV_MAGICCONST random.WichmannHill random.gauss random.paretovariate random.setstate
random.RECIP_BPF random.betavariate random.getrandbits random.randint random.shuffle
random.Random random.choice random.getstate random.random random.triangular
random.SG_MAGICCONST random.division random.jumpahead random.randrange random.uniform
In [10]: random.ra
random.randint random.random random.randrange
In [10]: random.randint(1,6)
Out[10]: 3
In [11]: random.randint(1,6)
Out[11]: 2
 
python內置函數,不需要導入模塊就可以用的函數
https://docs.python.org/2/library/functions.html
Built-in Functions
abs()
all()
any()
basestring()
bin()
bool()
bytearray()
callable()
chr()
classmethod()
cmp()
compile()
complex()
delattr()
dict()
dir()
divmod()
enumerate()
eval()
execfile()
file()
filter()
float()
format()
frozenset()
getattr()
globals()
hasattr()
hash()
help()
hex()
id()
input()
int()
isinstance()
issubclass()
iter()
len()
list()
locals()
long()
map()
max()
memoryview()
min()
next()
object()
oct()
open()
ord()
pow()
print()
property()
range()
raw_input()
reduce()
reload()
repr()
reversed()
round()
set()
setattr()
slice()
sorted()
staticmethod()
str()
sum()
super()
tuple()
type()
unichr()
unicode()
vars()
xrange()
zip()
__import__()
 
while循環
whle循環,直到表達式變為假,才退出while循環,表達式是一個邏輯表達式,必須返回一個True或False。
語法:
while expression:
statement(s)
else
while循環如果正常結束,才會執行else語句。
while...else的語法結構是,while循環正常執行完了會執行else后面的代碼
(也就是判斷條件正常結束 while i <= 10:),如果沒有正常執行完,即遇到了break,則不執行else后面的代碼
#!/usr/bin/python
x = ''
while x != 'q':
print 'hello'
x = raw_input("Please input something, q for quit: ")
if not x:
break
if x == 'quit':
continue
print 'continue'
else:
print 'world'
 
(繼續閱讀...)
文章標籤

AutoPoster 發表在 痞客邦 留言(0) 人氣(16)

  • 個人分類:生活學習
▲top
  • 3月 09 週四 201720:31
  • Python第五天 文件訪問 for循環訪問文件 while循環訪問文件 字符串的startswith函數和split函數


文章出處
Python第五天   文件訪問    for循環訪問文件    while循環訪問文件   字符串的startswith函數和split函數
 
目錄
Pycharm使用技巧(轉載)
Python第一天 安裝 shell 文件
Python第二天 變量 運算符與表達式 input()與raw_input()區別 字符編碼
Python第三天 序列 數據類型 數值 字符串 列表 元組 字典
Python第四天 流程控制 ifelse條件判斷 forwhile循環
Python第五天 文件訪問 for循環訪問文件 while循環訪問文件 字符串的startswith函數和split函數
Python第六天 類型轉換
Python第七天 函數 函數參數 函數變量 函數返回值 多類型傳值 冗余參數 函數遞歸調用 匿名函數 內置函數 列表表達式/列表重寫
Python第八天 模塊 包 全局變量和內置變量__name__ Python path
Python第九天 面向對象 類定義 類的屬性 類的方法 內部類 垃圾回收機制 類的繼承
Python第十天 print >> f,和fd.write()的區別 stdout的buffer 標準輸入 標準輸出 標準錯誤 重定向
Python第十一天 異常處理 glob模塊和shlex模塊 打開外部程序和subprocess模塊 subprocess類 Pipe管道 operator模塊 sorted函數 生成器 walk模塊 hashlib模塊
Python第十二天   收集主機信息   正則表達式   正則表達式  無名分組   有名分組
Python第十三天   django 1.6   導入模板   定義數據模型   訪問數據庫   GET和POST方法    SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊  django和web服務器整合  wsgi模塊   gunicorn模塊
Python第十四天 序列化  pickle模塊  cPickle模塊  JSON模塊  API的兩種格式
 
 
 
 
Python文件訪問
open
r:以讀方式打開
w :以寫方式打開,如果文件已經有內容,會覆蓋
a :以追加模式
r+ :以讀寫模式打開
w+:以讀寫模式打開 (參見 w )
a+:以讀寫模式打開 (參見 a )
rb:以二進制讀模式打開
wb:以二進制寫模式打開 (參見 w )
ab:以二進制追加模式打開 (參見 a )
rb+:以二進制讀寫模式打開 (參見 r+ )
wb+:以二進制讀寫模式打開 (參見 w+ )
ab+: 以二進制讀寫模式打開 (參見 a+)
with open :python2.6才有的方法,python2.5沒有,用with open,退出with open代碼塊之后的代碼不需要顯式fd.close()
#!/usr/bin/python
with open('/proc/meminfo') as fd:
for line in fd:
if line.startswith('MemTotal'):
total = line.split()[1]
continue
if line.startswith('MemFree'):
free = line.split()[1]
break
print "%.2f" % (int(free)/1024.0)+'M'
文件的方法
fd.close():不執行fd.close(),python程序退出的時候也會close文件
fd.read()
fd.readline()
fd.readlines() :返回一個列表,每個元素都會加上一個換行符\n
next():一行一行讀取
 
 
 
for循環訪問文件
第一種 readlines全部把文件內容讀到內存
#!/usr/bin/python
fd = open('/tmp/tmp.txt')
for line in fd.readlines():
print line,
--------------------------
第二種 一行一行的讀到內存 比較節省內存
#!/usr/bin/python
fd = open('/tmp/tmp.txt')
for line in fd:
print line,
這里的fd是一個對象,有fd.next()方法,是顯示文件一行,那么for i in fd就相當于一直在執行fd.next()方法,直到文件結束
 
while循環訪問文件
#!/usr/bin/python
with open('/tmp/tmp.txt') as fd:
while True:
line = fd.readline()
if not line:
break
print line,
 
字符串的startswith函數和split函數
startswith()函數:匹配字符串中的行,完全匹配,不能模糊匹配
split()函數:切割字符串,默認以空格為分隔符
isdigit()函數:判斷字符串是否是數字
string.digits函數:返回數字0123456789
 
 
 
#!/usr/bin/env python
import os
import sys
import string
def isNum(s):
for i in s:
if i in string.digits:
if i.isdigit():
continue
else:
return False
return True
if isNum(sys.argv[1]):
print sys.argv[1]

 
 
In [5]: a.isdigit()
Out[5]: False
#!/usr/bin/python
with open('/proc/meminfo') as fd:
for line in fd:
if line.startswith('MemTotal'):
total = line.split()[1]
continue
if line.startswith('MemFree'):
free = line.split()[1]
break
print "%.2f" % (int(free)/1024.0)+'M'
(繼續閱讀...)
文章標籤

AutoPoster 發表在 痞客邦 留言(0) 人氣(1)

  • 個人分類:生活學習
▲top
«1...181920230»

pop-under

參觀人氣

  • 本日人氣:
  • 累積人氣:

線上人數

Marquee

最新文章

  • 文章列表
  • jvm系列(四):jvm調優-命令大全(jps jstat jmap jhat jstack jinfo)
  • spring boot(一):入門篇
  • jvm系列(一):java類的加載機制
  • jvm系列(三):java GC算法 垃圾收集器
  • spring boot 實戰:我們的第一款開源軟件
  • jvm系列(六):jvm調優-從eclipse開始
  • 混合應用技術選型
  • jvm系列(二):JVM內存結構
  • spring boot(五):spring data jpa的使用

熱門文章

  • (1,763)jQuery之前端國際化jQuery.i18n.properties
  • (630)技術筆記:Indy控件發送郵件
  • (515)linux下安裝sqlite3
  • (501)學習筆記: Delphi之線程類TThread
  • (242)VC單選按鈕控件(Radio Button)用法(轉)
  • (104)單條件和多條件查詢
  • (51)淺談config文件的使用
  • (26)Tomcat shutdown執行后無法退出進程問題排查及解決
  • (22)基于 Asp.Net的 Comet 技術解析
  • (15)Java中的抽象類

文章分類

  • 生活學習 (2,296)
  • 未分類文章 (1)

最新留言

  • [20/04/24] 我是女生想約炮 有男生願意給我溫暖的嗎?我賴是woyou58 於文章「(1)從底層設計,探討插件式GIS框架的...」留言:
    我叫黎兒女生最近內心掙扎著要不要約炮我的line:woy...

文章搜尋

文章精選

誰來我家

Live Traffic Feed