'Python'에 해당되는 글 105건

  1. 2015.03.05 forInReadline.py
  2. 2015.03.05 cookie.py
  3. 2015.03.05 putSome.py
  4. 2015.03.05 withAsReadline.py
  5. 2015.03.05 fileReadline.py
  6. 2015.03.04 SimpleServer.py
  7. 2015.02.25 foo.py (feat. a conventional usage of 'self')
  8. 2015.02.25 MyClass.py (feat. __init__)
  9. 2015.02.25 pickleTrial.py
  10. 2015.02.25 chat_server2.py // chat_client2.py // communication.py
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


data=open('/python/email.py')
for line in data:
    if not line: break
    print (line)

'Python > Python 3.x' 카테고리의 다른 글

threadingLock.py  (0) 2015.03.06
threadingEx.py  (0) 2015.03.05
putSome.py  (0) 2015.03.05
withAsReadline.py  (0) 2015.03.05
foo.py (feat. a conventional usage of 'self')  (0) 2015.02.25
Posted by af334
2015. 3. 5. 04:54
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

#!/usr/local/bin/python26
"""
Python Session Handling

Note: A user must have cookies enabled!

TODO:
* Support Named Sessions

Copyright 2010 - Sunjay Varma

Latest Version: http://www.sunjay.ca/download/session.py
"""

import cgi
import os
import time
import errno
import hashlib
import datetime

from Cookie import SimpleCookie
from cPickle import dump, load, HIGHEST_PROTOCOL, dumps, loads

if not "HTTP_COOKIE" in os.environ:
    os.environ["HTTP_COOKIE"] = ""

SESSION = None

S_DIR = os.path.expanduser("~/.py_sessions") # expanduser for windows users
S_EXT = ".ps"
S_ID = "__sid__"

TODAY = str(datetime.date.today())
DEBUG = [] # debug messages

if not os.path.exists(S_DIR):
    os.makedirs(S_DIR)

class NoCookiesError(Exception): pass
class NotStarted(Exception): pass

class Session(object):

    def __init__(self):
        self.data = {}
        self.started = False
        self._flock = None
        self.expires = 0 # delete right away
       
        self.__sid = sid = self.__getsid()
        self.path = os.path.join(S_DIR, sid+S_EXT)

    def isset(self, name):
        """Is the variable set in the session?"""
        if not self.started:
            raise NotStarted("Session must be started")

        return name in self

    def unset(self, name):
        """Unset the name from the session"""
        if not self.started:
            raise NotStarted("Session must be started")
        del self[name]

    @staticmethod
    def __newsid():
        """Create a new session ID"""
        h = hashlib.new("ripemd160")
        h.update(str(time.time()/time.clock()**-1)+str(os.getpid()))
        return h.hexdigest()

    def __getsid(self):
        """Get the current session ID or return a new one"""
        # first, try to load the sid from the GET or POST forms
        form = cgi.FieldStorage()
        if form.has_key(S_ID):
            sid = form[S_ID].value
            return sid

        # then try to load the sid from the HTTP cookie
        self.cookie = SimpleCookie()
        if os.environ.has_key('HTTP_COOKIE'):
            self.cookie.load(os.environ['HTTP_COOKIE'])

            if S_ID in self.cookie:
                sid = self.cookie[S_ID].value
                return sid
        else:
            raise NoCookiesError("Could not find any cookies")

        # if all else fails, return a new sid
        return self.__newsid()

    def getsid(self):
        """
        Return the name and value that the sid needs to have in a GET or POST
        request
        """
        if not self.started:
            raise NotStarted("Session must be started")
        return (S_ID, self.__sid)

    def start(self):
        """Start the session"""
        if self.started:
            return True # session cannot be started more than once per script

        self._flock = FileLock(self.path)
        self._flock.acquire()

        # load the session if it exists
        if os.path.exists(self.path):
            with open(self.path, "rb") as f:
                self.data = dict(load(f))
                self.data["__date_loaded__"] = TODAY

        else: # create a session
            with open(self.path, "wb") as f:
                self.data = {"__date_loaded__":TODAY}

        # the session is officially started!
        self.started = True

        # store the sid in the cookie
        self.cookie[S_ID] = self.__sid
        self.cookie[S_ID]["expires"] = str(self.expires)
        self.cookie[S_ID]["version"] = "1"

        return True

    def commit(self):
        """Commit the changes to the session"""
        if not self.started:
            raise NotStarted("Session must be started")
        with open(self.path, "wb") as f:
            dump(self.data, f, HIGHEST_PROTOCOL)

    def destroy(self):
        """Destroy the session"""
        if not self.started:
            raise NotStarted("Session must be started")
        os.delete(self.path)
        if self._flock:
            self._flock.release()
        self.started = False

    def output(self):
        """Commit changes and send headers."""
        if not self.started:
            raise NotStarted("Session must be started")
        self.commit()
        return self.cookie.output()

    def setdefault(self, item, default=None):
        if not self.started:
            raise NotStarted("Session must be started")
        if not self.isset(item):
            self[item] = default

        return self[item]
       
    def set_expires(self, days):
        """Sets the expiration of the cookie"""
        date = datetime.date.today() + datetime.timedelta(days=days)
        self.expires = date.strftime("%a, %d-%b-%Y %H:%M:%S PST")
        self.cookie[S_ID]["expires"] = str(self.expires)

    def __getitem__(self, item):
        """Get the item from the session"""
        if not self.started:
            raise NotStarted("Session must be started")
        return self.data.__getitem__(item)

    def __setitem__(self, item, value):
        """set the item into the session"""
        if not self.started:
            raise NotStarted("Session must be started")
        self.data.__setitem__(item, value)

    def __delitem__(self, item):
        if not self.started:
            raise NotStarted("Session must be started")
        self.data.__delitem__(item)

    def __contains__(self, item):
        """Return if item in the session"""
        if not self.started:
            raise NotStarted("Session must be started")
        return self.data.__contains__(item)

    def __iter__(self):
        """Go through the names of all the session variables"""
        if not self.started:
            raise NotStarted("Session must be started")
        return self.data.__iter__()

def start():
    global SESSION
    SESSION = Session()
    return SESSION.start()

def destroy():
    global SESSION
    if SESSION:
        SESSION.destroy()

def get_session():
    global SESSION
    if not SESSION:
        SESSION = Session()
    return SESSION

### The following is a (little) modified version of this:
# http://www.evanfosmark.com/2009/01/cross-platform-file-locking-support-in-
# python/

class FileLockException(Exception):
    pass

class FileLock(object):
    """ A file locking mechanism that has context-manager support so
        you can use it in a with statement. This should be relatively cross
        compatible as it doesn't rely on msvcrt or fcntl for the locking.
    """

    def __init__(self, file_name, timeout=10, delay=.05):
        """ Prepare the file locker. Specify the file to lock and optionally
            the maximum timeout and the delay between each attempt to lock.
        """
        self.is_locked = False
        self.lockfile = os.path.join(os.getcwd(), "%s.lock" % file_name)
        self.file_name = file_name
        self.timeout = timeout
        self.delay = delay

    def acquire(self):
        """ Acquire the lock, if possible. If the lock is in use, it check again
            every `wait` seconds. It does this until it either gets the lock or
            exceeds `timeout` number of seconds, in which case it throws
            an exception.
        """
        if self.is_locked:
            return

        start_time = time.time()
        while True:
            try:
                self.fd = os.open(self.lockfile, os.O_CREAT|os.O_EXCL|os.O_RDWR)
                break;
            except OSError as e:
                if e.errno != errno.EEXIST:
                    raise

                if (time.time() - start_time) >= self.timeout:
                    raise FileLockException("Timeout occured.")
                time.sleep(self.delay)
        self.is_locked = True

    def release(self):
        """ Get rid of the lock by deleting the lockfile.
            When working in a `with` statement, this gets automatically
            called at the end.
        """
        if self.is_locked:
            os.close(self.fd)
            os.unlink(self.lockfile)
            self.is_locked = False

    def __enter__(self):
        """ Activated when used in the with statement.
            Should automatically acquire a lock to be used in the with block.
        """
        if not self.is_locked:
            self.acquire()
        return self

    def __exit__(self, type, value, traceback):
        """ Activated at the end of the with statement.
            It automatically releases the lock if it isn't locked.
        """
        if self.is_locked:
            self.release()

    def __del__(self):
        """ Make sure that the FileLock instance doesn't leave a lockfile
            lying around.
        """
        self.release()

def print_session(session):
    """
    Prints info from the current session.

    WARNING: ONLY FOR DEBUGGING. MAJOR SECURITY RISK!
    """
    print "<h3>Session Data</h3>"
    print "<dl>"
    for name in session:
        print "<dt>%s <i>%s</i></dt>"%(name, type(session[name]))
        print "<dd>%s</dd>"%repr(session[name])
    print "</dl>"

def main():
    """Tester Program"""

    start() # session.start()
    if SESSION.isset("views"):
        SESSION["views"] += 1
    else:
        SESSION["views"] = 1

    print "Content-type: text/html"
    print SESSION.output()
    print

    print "<html><head><title>Session Testing</title></head><body>"
    print "<h2>You have viewed this page %i times.</h2>"%SESSION["views"]
    print_session(SESSION)
    print "<p>", SESSION.path, "</p>"
    for line in DEBUG:
        print "<p>%s</p>"%line
    print "<p>%s</p>"%SESSION.data
    print "</body></html>"

if __name__ == "__main__":
    main()

'Python' 카테고리의 다른 글

threadingQueue.py  (0) 2015.03.06
threadEx.py  (0) 2015.03.05
fileReadline.py  (0) 2015.03.05
SimpleServer.py  (0) 2015.03.04
chat_server2.py // chat_client2.py // communication.py  (0) 2015.02.25
Posted by af334
2015. 3. 5. 02:43
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

import sys


print('put some : ')
a=sys.stdin.readline().strip()
print(a)


'Python > Python 3.x' 카테고리의 다른 글

threadingEx.py  (0) 2015.03.05
forInReadline.py  (0) 2015.03.05
withAsReadline.py  (0) 2015.03.05
foo.py (feat. a conventional usage of 'self')  (0) 2015.02.25
MyClass.py (feat. __init__)  (0) 2015.02.25
Posted by af334
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


with open('/python/email.py') as data_file:
    while 1:
        line=data_file.readline()
        if not line :break
        print(line)

'Python > Python 3.x' 카테고리의 다른 글

forInReadline.py  (0) 2015.03.05
putSome.py  (0) 2015.03.05
foo.py (feat. a conventional usage of 'self')  (0) 2015.02.25
MyClass.py (feat. __init__)  (0) 2015.02.25
pickleTrial.py  (0) 2015.02.25
Posted by af334
2015. 3. 5. 02:22
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


data_file=open('/python/email.py')

while 1:
    line=data_file.readline()
    if not line: break
    print(line)

data_file.close()


'Python' 카테고리의 다른 글

threadEx.py  (0) 2015.03.05
cookie.py  (0) 2015.03.05
SimpleServer.py  (0) 2015.03.04
chat_server2.py // chat_client2.py // communication.py  (0) 2015.02.25
pygameScreen.py  (0) 2015.02.20
Posted by af334
2015. 3. 4. 02:31
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

import SimpleHTTPServer
import SocketServer

PORT=8000

Handler=SimpleHTTPServer.SimpleHTTPRequestHandler

httpd=SocketServer.TCPServer(("",PORT), Handler)

print "serving at port",PORT
httpd.serve_forever()


==================


python -m SimpleServer 8000



'Python' 카테고리의 다른 글

cookie.py  (0) 2015.03.05
fileReadline.py  (0) 2015.03.05
chat_server2.py // chat_client2.py // communication.py  (0) 2015.02.25
pygameScreen.py  (0) 2015.02.20
getMac.py  (0) 2015.02.20
Posted by af334
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

class foo:
    def bar(self):
        print ("hi")

class foo2:
    def bar2(s):
        print ("hihi")


f=foo()
f.bar()

ff=foo2()
ff.bar2()



'Python > Python 3.x' 카테고리의 다른 글

putSome.py  (0) 2015.03.05
withAsReadline.py  (0) 2015.03.05
MyClass.py (feat. __init__)  (0) 2015.02.25
pickleTrial.py  (0) 2015.02.25
chat_server / chat_client  (0) 2015.02.21
Posted by af334
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

class MyClass(object):
    i=123
    def __init__(self):
        self.i=345


a=MyClass()
print (a.i)    #345

print(MyClass.i)        #123

'Python > Python 3.x' 카테고리의 다른 글

putSome.py  (0) 2015.03.05
withAsReadline.py  (0) 2015.03.05
foo.py (feat. a conventional usage of 'self')  (0) 2015.02.25
pickleTrial.py  (0) 2015.02.25
chat_server / chat_client  (0) 2015.02.21
Posted by af334
2015. 2. 25. 17:08
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

import pickle
import sqlite3
from collections import namedtuple

#Simple class representing a record in our database
MemoRecord=namedtuple("MemoRecord", "key, task")

class DBPickler(pickle.Pickler):
    def persistent_id(self,obj):
        #Instead of pickling MemoRecord as a regular class instance, we emit a
        # persistent ID
        if isinstance(obj, MemoRecord):
            #Here, our persistent ID is simply a tuple, containing a tag and a
            #key, which refers to a specific record in the database
            return ("MemoRecord",obj.key)
        else:
            #If obj does not have a persistent ID, return None. This means obj
            #needs to be pickled as usual
            return None


class DBUnpickler(pickle.Unpickler):
    def __init__(self,file,connection):
        super().__init__(file)
        self.connection=connection

    def persistent_load(self,pid):
        #This method is invoked whenever a persistent ID is encountered
        #Here, pid is the tuple returned by DBPickler
        cursor=self.connection.cursor()
        type_tag, key_id=pid
        if type_tag=="MemoRecord":
            #Fetch the regerenced record from the database and return it
            cursor.execute("SELECT * FROM memos WHERE key=?",(str(key_id),))
            key, task=cursor.fetchone()
            return MemoRecord(key, task)
        else:
            # Always raises an error if you cannot return the correct object
            # Otherwise, the unpickler will think None is the object referenced
            # by the persistent ID
            raise pickle.UnpicklingError("unsupported persistent object")



def main():
    import io
    import pprint

    # Initialize and populate our database
    conn=sqlite3.connect(":memory:")
    cursor=conn.cursor()
    cursor.execute("CREATE TABLE memos(key INTEGER PRIMARY KEY, task TEXT)")
    tasks=(
        'give food to fish',
        'prepare group meeting',
        'fight with a zebra',
        )
    for task in tasks:
        cursor.execute("INSERT INTO memos VALUES(NULL,?)",(task,))

    #Fetch the records to be pickled
    cursor.execute("SELECT * FROM memos")
    memos=[MemoRecord(key,task) for key, task in cursor]
    #Save the records using our custom DBPickler
    file =io.BytesIO()
    DBPickler(file).dump(memos)

    print("Pickled records:")
    pprint.pprint(memos)

    #Update a record, just for good measure
    cursor.execute("UPDATE memos SET task='learn italian' WHERE key=1")

    #Load the records from the pickle data stream
    file.seek(0)
    memos=DBUnpickler(file, conn).load()

    print("Unpickled records:")
    pprint.pprint(memos)


if __name__=='__main__':
    main()

'Python > Python 3.x' 카테고리의 다른 글

putSome.py  (0) 2015.03.05
withAsReadline.py  (0) 2015.03.05
foo.py (feat. a conventional usage of 'self')  (0) 2015.02.25
MyClass.py (feat. __init__)  (0) 2015.02.25
chat_server / chat_client  (0) 2015.02.21
Posted by af334
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

chat_server2.py



import select
import socket
import sys
import signal
from communication import send, receive

BUFSIZ=1024

class ChatServer(object):
    """Simple chat server using select """
    def __init__(self,port=3490, backlog=5):
        self.clients=0
        #Client map
        self.clientmap={}
        #Outputsocket list
        self.outputs=[]
        self.server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
        self.server.bind(('',port))
        print 'Listening to port',port,'...'
        self.server.listen(backlog)
        #Trap keyboard interrupts
        signal.signal(signal.SIGINT, self.sighandler)

    def sighandler(self, signum,frame):
        #Close the server
        print 'Shutting down server...'
        #Close existing client sockets
        for o in self.outputs:
            o.close()

        self.server.close()

    def getname(self, client):
        # Return the printable name of the client, given its socket...
        info=self.clientmap[client]
        host,name=info[0][0], info[1]
        return '@'.join((name,host))

    def serve(self):
        inputs=[self.server,sys.stdin]
        self.outputs=[]

        running =1

        while running:
            try:
                inputready, outputready, exceptready=select.select(inputs, self.outputs,[])
            except select.error,e:
                break
            except socket.error, e:
                break

            for s in inputready:
                if s==self.server:
                    #handle the server socket
                    client, address=self.server.accept()
                    print 'chatserver: got connection %d from %s' %(client.fileno(),address)
                    #Read the login name
                    cname=receive(client).split('NAME: ')[1]

                    # Computer client name and send back
                    self.clients+=1
                    send(client, 'CLIENT: '+str(address[0]))
                    inputs.append(client)

                    self.clientmap[client]=(address,cname)
                    #Send joining information to other clients
                    msg='\n(Connected: New client(%d) from %s)' %(self.clients,self.getname(client))
                    for o in self.outputs:
                        # o.send(msg)
                        send(o,msg)

                    self.outputs.append(client)

                elif s==sys.stdin:
                    #handle standard input
                    junk=sys.stdin.readline()
                    running=0
                else:
                    # handle all other sockets
                    try:
                        #data=s.recv(BUFSIZ)
                        data=receive(s)
                        if data:
                            #send as new client 's message...'
                            msg='\n#['+self.getname(s)+']>> '+data
                            #send data to all except ourselves
                            for o in self.outputs:
                                if o!=s:
                                    #o.send(msg)
                                    send(o,msg)
                        else:
                            print 'chatserver: %d hung up' % s.fileno()
                            self.clients-=1
                            s.close()
                            inputs.remove(s)
                            self.outputs.remove(s)

                            #Send client leaving informatio to others
                            msg='\n(Hung up: Client from %s' %self.getname(s)
                            for o in self.outputs:
                                #o.send(msg)
                                send(o,msg)

                    except socket.error,e:
                        #remove
                        inputs.remove(s)
                        self.outputs.remove(s)

        self.server.close()

if __name__=="__main__":
    ChatServer().serve()



============================


chat_client2.py



import socket
import sys
import select
from communication import send, receive

BUFSIZ=1024

class ChatClient(object):
    """ A simple command line chat client using select """
    def __init__(self,name,host='127.0.0.1',port=3490):
        self.name=name
        #Quit flag
        self.flag=False
        self.port=int(port)
        self.host=host
        #Initial prompt
        self.prompt='['+'@'.join((name,socket.gethostname().split('.')[0]))+']> '
        #Connect to server at port
        try:
            self.sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect((host,self.port))
            print 'Connected to chat server@%d' %self.port
            #Send my name...
            send(self.sock, 'NAME: '+self.name)
            data=receive(self.sock)
            #Contains client address, set it
            addr=data.split('CLIENT: ')[1]
            self.prompt='['+'@'.join((self.name,addr))+']> '
        except socket.error,e :
            print 'Could not conenct to chat server @%d'%self.port
            sys.exit(1)

    def cmdloop(self):
        while not self.flag:
            try:
                sys.stdout.write(self.prompt)
                sys.stdout.flush()
   
                #Wait for input from stdin & socket
                inputready, outputready, exceptrdy=select.select([0,self.sock], [], [])
   
                for i in inputready:
                    if i ==0:
                        data=sys.stdin.readline().strip()
                        if data:send(self.sock,data)
                    elif i==self.sock:
                        data=receive(self.sock)
                        if not data:
                            print 'Shutting down'
                            self.flag=True
                            break
                        else:
                            sys.stdout.write(data+'\n')
                            sys.stdout.flush()
   
            except KeyboardInterrupt:
                print 'Interrupted.'
                self.sock.close()
                break


if __name__=="__main__":
    import sys

    if len(sys.argv)<3:
        sys.exit('Usage: %s chatid host portno'% sys.argv[0])

    client=ChatClient(sys.argv[1], sys.argv[2], int(sys.argv[3]))
    client.cmdloop()



==========================


communication.py


import cPickle
import socket
import struct

marshall=cPickle.dumps
unmarshall=cPickle.loads

def send(channel, *args):
    buf=marshall(args)
    value=socket.htonl(len(buf))
    size=struct.pack("L",value)
    channel.send(size)
    channel.send(buf)

def receive(channel):
    size=struct.calcsize("L")
    size=channel.recv(size)
    try:
        size=socket.ntohl(struct.unpack("L",size)[0])
    except struct.error, e:
        return ''

    buf=""

    while len(buf)<size:
        buf=channel.recv(size-len(buf))

    return unmarshall(buf)[0]















'Python' 카테고리의 다른 글

fileReadline.py  (0) 2015.03.05
SimpleServer.py  (0) 2015.03.04
pygameScreen.py  (0) 2015.02.20
getMac.py  (0) 2015.02.20
monotonicTIme.py  (0) 2015.02.18
Posted by af334
이전버튼 1 2 3 4 5 6 7 ··· 11 이전버튼