| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2431 人关注过本帖
标题:python网络编程
取消只看楼主 加入收藏
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
结帖率:40%
收藏
 问题点数:0 回复次数:7 
python网络编程
from socket import *
from time import ctime
from ftplib import FTP
def runTcp():
    host = ""
    port = 21567
    addr = (host,port)
    BUFSIZ = 1024
    tcpSock = socket(AF_INET, SOCK_STREAM)
    tcpSock.bind(addr)
    tcpSock.listen(5)      
    while True:
        tcpCliSock, addr=tcpSock.accept()
        print '...connected from:', addr
        data = tcpCliSock.recv(BUFSIZ)
        if data=="quit":
            break
        tcpCliSock.send('[%s] %s' % (ctime(), data))
        
    tcpCliSock.close()
    tcpSock.close()
def udprun():
    host = ""
    port = 21567
    addr = (host,port)
    BUFSIZ = 1024
    udpSerSock = socket(AF_INET, SOCK_DGRAM)
    udpSerSock.bind(addr)
    while True:
        print 'waiting for message...'
        data, addr = udpSerSock.recvfrom(BUFSIZ)
        print 'waiting for message...',addr
        udpSerSock.sendto('[%s] %s' % (ctime(), data), addr)
        print '...received from and returned to:', addr
        if not data:
            break
    udpSerSock.close()
   
if __name__ == '__main__':
        runTcp()
   
搜索更多相关主题的帖子: import python 网络编程 connected 
2013-10-30 11:24
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
from socket import *
def runclietn():
    HOST = 'localhost'
    PORT = 21567
    BUFSIZ = 1024
    ADDR = (HOST, PORT)
    tcpCliSock = socket(AF_INET, SOCK_STREAM)
    tcpCliSock.connect(ADDR)
    while True:
        data = raw_input('> ')

        tcpCliSock.send(data)
        data = tcpCliSock.recv(BUFSIZ)
        print data

    tcpCliSock.close()
def runUdpclient():
    HOST = 'localhost'
    PORT = 21567
    BUFSIZ = 1024
    ADDR = (HOST, PORT)
    udpCliSock = socket(AF_INET, SOCK_DGRAM)
    while True:
        data = raw_input('> ')
        if not data:
            break
        udpCliSock.sendto(data, ADDR)
        data, ADDR = udpCliSock.recvfrom(BUFSIZ)
        if not data:
            break
        print "dataudpCliSock.close()",data

    udpCliSock.close()   
if __name__ == '__main__':
        runclietn()
2013-10-30 11:24
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
import ftplib
import os
import socket

HOST = '109.119.20.178'
DIRN = 'pub/'
FILE = 'bugzilla-LATEST.tar.gz'

def main():
    try:
        f = ftplib.FTP(HOST)
    except (socket.error, socket.gaierror), e:
        print 'ERROR: cannot reach "%s"' % HOST
        return
    print '*** Connected to host "%s"' % HOST

    try:
        f.login('root','123')
    except ftplib.error_perm:
        print r'ERROR: cannot login anonymously'
        f.quit()
        return
    print '*** Logged in as "anonymous"'

    try:
        f.cwd(DIRN)
    except ftplib.error_perm:
        print 'ERROR: cannot CD to "%s"' % DIRN
        f.quit()
        return
    print '*** Changed to "%s" folder' % DIRN
    try:
        f.retrbinary('RETR %s' % FILE,open(FILE, 'wb').write)
    except ftplib.error_perm:
        print 'ERROR: cannot read file "%s"' % FILE
        os.unlink(FILE)
    else:
        print '*** Downloaded "%s" to CWD' % FILE
        f.quit()
        return

if __name__ == '__main__':
    main()
2013-10-30 11:25
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
import web
web.config.debug = False

urls = ("/hello/(.+)", "hello",
        "/count", "count",
        "/reset", "reset"
       )
web.config.debug = False

app = web.application(urls, globals())
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'count': 0})


class hello:
    def GET(self,id):
        idk=str(id)
        referer =web.ctx.get('HTTP_REFERER', 'http://www.')
        print web.ctx.path
        raise web.seeother(referer)

    def POST(self,planId):
        return 'Hello, world!'+planId
   
class count:
    def GET(self):
        session.count += 1
        print session.count
        return str(session.count)

class reset:
    def GET(self):
        session.kill()
        return ""




if __name__ == "__main__":
    app.run()
2013-10-30 11:25
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
import urllib


from sgmllib import SGMLParser
class urllister(SGMLParser):
    def reset(self):
        SGMLParser.reset(self)
        self.urls=[]
    def start_meta(self,attrs):
        print attrs
        href=[v for k,v in attrs if k=="http-equiv"]
        print locals()
        if href:
            self.urls.extend(href)

s=urllib.urlopen("http://www.baidu.com")
html=s.read()
print html
parser=urllister()
parser.feed(html)
parser.close()
s.close()
2013-10-30 11:26
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
import httplib
import urllib
#feeddata = urllib.urlopen('http://www.baidu.com').read()
#print feeddata

import urllib2
#request = urllib2.Request('http://localhost:8080/disaster/start/1')
httpClient = httplib.HTTPConnection("localhost", "8080", timeout=1)
params={"disaster_type":"hhhhh"}
param = urllib.urlencode(params);
#get
#httpClient.request('GET', "/disaster/start/HHHH")
httpClient.request('GET', "/disaster/start/u",param)
response = httpClient.getresponse()
read=response.read()
print read
"""request.add_header('User-Agent','OpenAnything/1.0 +http://')
print request.get_host()
opener = urllib2.build_opener()
feeddata = opener.open(request).read()

print opener.open(request).headers.dict.keys()
print feeddata


class DefaultErrorHandler(urllib2.HTTPDefaultErrorHandler):
    def http_error_default(self, req, fp, code, msg, headers):
        result = urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
        result.status = code
        return result
opener = urllib2.build_opener(DefaultErrorHandler())
request.add_header('Accept-encoding', 'gzip')

seconddatastream = opener.open(request)
print seconddatastream.headers.get('Content-Encoding')"""
2013-10-30 11:26
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
import pymongo

con = pymongo.Connection('localhost', 27017)
mydb = con.mydb#创建数据库
print  mydb

mydb.add_user('test', 'test') # add a user
print mydb.authenticate('test', 'test') # check auth

muser = mydb.user # new a table

 
muser.save({'id':1, 'name':'test'}) # add a record

muser.insert({'id':2, 'name':'hello'}) # add a record
print  muser.find_one() # find a record

print muser.find_one({'id':2}) # find a record by query
 
muser.create_index('id')

print muser.find().sort('id', pymongo.ASCENDING) # DESCENDING
# muser.drop() delete table
print muser.find({'id':1}).count() # get records number

print muser.find({'id':1}).limit(3).skip(2) # start index is 2 limit 3 records

muser.remove({'id':1}) # delet records where id = 1
 
muser.update({'id':2}, {'$set':{'name':'haha'}}) # update one recor
2013-10-30 11:27
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
from mongoengine import *
SIZE = (('S', 'Small'),
        ('M', 'Medium'),
        ('L', 'Large'),
        ('XL', 'Extra Large'),
        ('XXL', 'Extra Extra Large'))
#连接数据库
connect('test')
class User(Document):
    name = StringField(required=False,unique=False)

class Page(Document):
    content = StringField(db_field="keyname",name="mongoengine name",default="default content")
    #一对一
    #author = ReferenceField(User)
    answers = DictField()
    values = ListField(IntField(), default=list)
    size = StringField(max_length=3, choices=SIZE)
    #一对多
    authors = ListField(ReferenceField(User))
    def to_dict(self):
        page = {}
        page['content'] = str(self.content)
        page['answers'] = self.answers
        page['values'] = self.values
        page['size'] = self.size
        page['authors'] = self.authors
        return page


class Employee(Document):
    name = StringField()
    boss = ReferenceField('self')
    profile_page = ReferenceField('ProfilePage')

class ProfilePage(Document):
    content = StringField()


'''
john = User(name="John Smith")
john.save()
#john.drop_collection()
post = Page(content="Test Page")
post.answers={"p":"j"}
#一对一
post.author = john
post.values=[1,2]
post.size="S"
post.save()
#post.delete()
#post.drop_collection()


#一对多   
bob = User(name="Bob Jones").save()
john = User(name="John Smith").save()
Page(content="Test Page", authors=[bob, john]).save()
Page(content="Another Page", authors=[john]).save() '''

#定义数据库别名和数据库名字   
register_connection('book-db',"book")
register_connection('users-books-db',"author")
#保存到对应别名的数据库
class Book(Document):   
    name = StringField()   
    meta = {"db_alias": "book-db"}   
class AcBook(Document):   
    name = StringField()   
    meta = {"db_alias": "book-db"}   
class AuthorBooks(Document):   
    book = ReferenceField(Book)   
    meta = {"db_alias": "users-books-db"}   
  
john = Book(name="John Smith")
john.save()
john1 = AcBook(name="John Smith")
john1.save()
john1.drop_collection()
post = AuthorBooks(book=john)
post.save()
2013-10-30 11:27
快速回复:python网络编程
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.030087 second(s), 10 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved