Ответы пользователя по тегу JavaScript
  • Как передать из python скрипта json для ajax запроса?

    sumej
    @sumej
    DevOps
    >сделать сайт учета студентов
    учёт оценок? посещаемости?
    >И какую бд лучше использовать если условия задания такого
    >Предполагаются частые выборки по фильтрам (включая комбинации): фамилия, группа, семестр, средний балл
    Поиск можно и через сфинкс можно и через майскуэль Полнотекстовый поиск и его возможности


    >Студенты могут часто переходить из одной группы в другую
    Не нагрузка.
    >Предполагаются частые выборки по фильтрам (включая комбинации): фамилия, группа, семестр, средний балл
    >Студентов будет много (порядка 1-2 млн)
    Если sql не справляется на SELECT. Тогда нужно будет думать =)

    >И как правильно вообще начинать писать без фреймворка?
    from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
    from os import curdir, sep
    
    PORT_NUMBER = 8080
    
    #This class will handles any incoming request from
    #the browser 
    class myHandler(BaseHTTPRequestHandler):
    	
    	#Handler for the GET requests
    	def do_GET(self):
    		if self.path=="/":
    			self.path="/index_example2.html"
    
    		try:
    			#Check the file extension required and
    			#set the right mime type
    
    			sendReply = False
    			if self.path.endswith(".html"):
    				mimetype='text/html'
    				sendReply = True
    			if self.path.endswith(".jpg"):
    				mimetype='image/jpg'
    				sendReply = True
    			if self.path.endswith(".gif"):
    				mimetype='image/gif'
    				sendReply = True
    			if self.path.endswith(".js"):
    				mimetype='application/javascript'
    				sendReply = True
    			if self.path.endswith(".css"):
    				mimetype='text/css'
    				sendReply = True
    
    			if sendReply == True:
    				#Open the static file requested and send it
    				f = open(curdir + sep + self.path) 
    				self.send_response(200)
    				self.send_header('Content-type',mimetype)
    				self.end_headers()
    				self.wfile.write(f.read())
    				f.close()
    			return
    
    
    		except IOError:
    			self.send_error(404,'File Not Found: %s' % self.path)
    
    try:
    	#Create a web server and define the handler to manage the
    	#incoming request
    	server = HTTPServer(('', PORT_NUMBER), myHandler)
    	print 'Started httpserver on port ' , PORT_NUMBER
    	
    	#Wait forever for incoming htto requests
    	server.serve_forever()
    
    except KeyboardInterrupt:
    	print '^C received, shutting down the web server'
    	server.socket.close()

    >Запись в эти таблицы будет вестись в конкурентом режиме доступа. Возможно нужно будет использовать блокировки либо всю работу спрятать в транзакции sql:
    import threading
    class Repository:
        def __init__(self):       
            self.__lock=threading.Lock()
       def add(self):
           with self.__lock:
                with open(self.config_path,"r") as json_data:
                    try:
                        data = json.load(json_data)
                    except:
                        logging.critical( "FATAL!!!can't read %s" % data)
                        raise ValueError("can't json.load(%s)" % data)

    import MySQLdb
    #Start a connection
    db= MySQLdb.connect(host="dbhost", user="dbuser" , passwd="dbpass", db="dbname")
    db.autocommit(False)
    cursor = db.cursor()
    try:
     cursor.execute("Your SQL")
     cursor.execute("Another sql")
     db.commit()
    except:
     db.rollback()

    запуск uwsgi --ini env.ini того же Flask/Falcon/etc
    env.ini:
    # it's example how run
    [uwsgi]
    plugins = python27
    http-socket = :80
    #pythonpath = /srv/myapp
    #virtualenv  = /home/project/ve
    chdir = /home/project
    processes = 1
    threads = 4
    #pythonpath = ..
    module = manager:app
    # This line below was important
    #wsgi-file = manager.py
    #callable = app
    # Turn this off for production
    catch-exceptions = true
    stats = /.tmp/.uwsgi-stats.socket
    touch-reload = /.tmp/.uwsgi-reload
    Ответ написан
    Комментировать