<commit_before>#!/usr/bin/env python

# To run:
# ./main.py
# and visit localhost:8888

# todo
# add api support for retrieving a record with the tagid
# fix files
# printing!
# add support for appending to existing tag/story
# add timezone to datetime in response

import tornado.httpserver
import tornado.ioloop
import tornado.web
import urllib, urllib2
import os, datetime, subprocess
from gridfs import GridFS

try:
    import json
except:
    import simplejson as json
import pymongo

# settings
DATABASE_NAME = 'demo_database'
TABLE_NAME = 'demo_table'

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')

class UploadHandler(tornado.web.RequestHandler):
    ''' base class for the web and api handlers. subclasses need to
    implement the self.post_processing() method for any additional
    processing. '''
    def post_processing(self, tag_id):
        ''' implemented by sub class'''
        pass

    def db_save(self, thistag):
        db = pymongo.Connection()[settings['database']]

        # if there's a file, store it using gridFS and replace the
        # file body in thistag, with reference to the file in
        # gridFS (the file_id)
#        if thistag.get('filebody', None):
#            gfs = GridFS(db)
#            file_id = gfs.put(thistag['filebody'], thistag['content_type'])
#            print 'filebody'
#            print thistag['filebody']
#            del thistag['filebody']
#            thistag['file'] = file_id

        # create 'body' as a list; there might be more body
        # elements added if multiple people edit the same tag
        thistag['created'] = datetime.datetime.now()
        tag = {'contents': [thistag,],
               'last_updated' : thistag['created']
               }        
        table = db[settings['table']]
        _id = table.insert(tag, safe=True)
        db.connection.disconnect()
        return _id

    def post(self):
        context = {}
        # arguments is a dict of key:value pairs where each value is a
        # list (even if there is only one item). 
        form = self.request.arguments
        print 'Arguments were:'
        print form
        print 'files submitted were:'
        print self.request.files

        # make sure the user submitted at least one of the fields:
        if self.get_argument('body', "") == "" and not self.request.files.get('file', None):
            self.set_secure_cookie("message", "You must submit either a message or a file")
            self.redirect('/')
            return        

        # build the new tag
        newtag = {}
        if self.get_argument('body', None):
            newtag['body'] = self.get_argument('body')

        if self.request.files.get('file', None):
            newtag['filebody'] = self.request.files['file'][0]['body']
            newtag['content_type'] = self.request.files['file'][0]['content_type']

        # save it to the db and create a uri for the content
        try:
            print 'newtag will be created with the following information'
            print newtag
            tag_id = self.db_save(newtag)
            context['tag_id'] = tag_id
        except BaseException, e:
            print 'there was an error from mongo:'
            print e
            self.write("There was a problem")
            return

        self.post_processing(tag_id)

def jsonify(record):
    ''' takes a record an converts the datetime objects and object ID
    to string, and returns it as a json-encoded string'''
    record['_id'] = str(record['_id'])
    record['last_updated'] = record['last_updated'].strftime("%Y/%m/%d %H:%M:%S")
    items = []
    for item in record['contents']:
        item['created'] = item['created'].strftime("%Y/%m/%d %H:%M:%S")
        items.append(item)
    record['contents'] = items
    js = json.dumps(record)
    return js

def print(img_data):    
    # generate the command to print the file. subprocess takes a list
    # or arguments, hence the call to split()
    tmpfile = '/tmp/qrcode.png'
    fp = open(tmpfile, 'w')
    fp.write(img_data)
    fp.close()
    print_file = 'lp -d SUNLIGHT_LABEL_PRINTER -o someopt -o otheropt '.split() + [tmpfile]
    subprocess.call(print_file)
    

class APIUploadHandler(UploadHandler):
    def post_processing(self, tag_id):
        ''' returns a json object with the tag/story contents'''

        record = get_record(self, tag_id)        
        js = jsonify(record)
        print 'will send response:'
        print js
        self.set_header("Content-Type", "application/json")
        self.write(js)
        return

class WebUploadHandler(UploadHandler):
    def post_processing(self, tag_id):

        # generate the qr code and send it to printer
        qr_url = create_qr(tag_uri(tag_id))<commit_msg>fixed name of print function to a non-keyword<commit_after>#!/usr/bin/env python

# To run:
# ./main.py
# and visit localhost:8888

# todo
# s3 files
# printing!
# add support for appending to existing tag/story
# add timezone to datetime in response

import tornado.httpserver
import tornado.ioloop
import tornado.web
import urllib, urllib2
import os, datetime, subprocess
from gridfs import GridFS

try:
    import json
except:
    import simplejson as json
import pymongo

# settings
DATABASE_NAME = 'demo_database'
TABLE_NAME = 'demo_table'

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')

class UploadHandler(tornado.web.RequestHandler):
    ''' base class for the web and api handlers. subclasses need to
    implement the self.post_processing() method for any additional
    processing. '''
    def post_processing(self, tag_id):
        ''' implemented by sub class'''
        pass

    def save(self, thistag):
        db = pymongo.Connection()[settings['database']]

        # if there's a file, store it using gridFS and replace the
        # file body in thistag, with reference to the file in
        # gridFS (the file_id)
#        if thistag.get('filebody', None):
#            gfs = GridFS(db)
#            file_id = gfs.put(thistag['filebody'], thistag['content_type'])
#            print 'filebody'
#            print thistag['filebody']
#            del thistag['filebody']
#            thistag['file'] = file_id

        # create 'body' as a list; there might be more body
        # elements added if multiple people edit the same tag
        thistag['created'] = datetime.datetime.now()
        tag = {'contents': [thistag,],
               'last_updated' : thistag['created']
               }        
        table = db[settings['table']]
        _id = table.insert(tag, safe=True)
        db.connection.disconnect()
        return _id

    def post(self):
        context = {}
        # arguments is a dict of key:value pairs where each value is a
        # list (even if there is only one item). 
        form = self.request.arguments
        print 'Arguments were:'
        print form
        print 'files submitted were:'
        print self.request.files

        # make sure the user submitted at least one of the fields:
        if self.get_argument('body', "") == "" and not self.request.files.get('file', None):
            self.set_secure_cookie("message", "You must submit either a message or a file")
            self.redirect('/')
            return        

        # build the new tag
        newtag = {}
        if self.get_argument('body', None):
            newtag['body'] = self.get_argument('body')

        if self.request.files.get('file', None):
            newtag['filebody'] = self.request.files['file'][0]['body']
            newtag['content_type'] = self.request.files['file'][0]['content_type']

        # save it to the db and create a uri for the content
        try:
            print 'newtag will be created with the following information'
            print newtag
            tag_id = self.save(newtag)
            context['tag_id'] = tag_id
        except BaseException, e:
            print 'there was an error from mongo:'
            print e
            self.write("There was a problem")
            return

        self.post_processing(tag_id)

def jsonify(record):
    ''' takes a record an converts the datetime objects and object ID
    to string, and returns it as a json-encoded string'''
    record['_id'] = str(record['_id'])
    record['last_updated'] = record['last_updated'].strftime("%Y/%m/%d %H:%M:%S")
    items = []
    for item in record['contents']:
        item['created'] = item['created'].strftime("%Y/%m/%d %H:%M:%S")
        items.append(item)
    record['contents'] = items
    js = json.dumps(record)
    return js

def printqr(img_data):    
    # generate the command to print the file. subprocess takes a list
    # or arguments, hence the call to split()
    tmpfile = '/tmp/qrcode.png'
    fp = open(tmpfile, 'w')
    fp.write(img_data)
    fp.close()
    print_file = 'lp -d SUNLIGHT_LABEL_PRINTER -o someopt -o otheropt '.split() + [tmpfile]
    subprocess.call(print_file)
    

class APIUploadHandler(UploadHandler):
    def post_processing(self, tag_id):
        ''' returns a json object with the tag/story contents'''

        record = get_record(self, tag_id)        
        js = jsonify(record)
        print 'will send response:'
        print js
        self.set_header("Content-Type", "application/json")
        self.write(js)
        return

class WebUploadHandler(UploadHandler):
    def post_processing(self, tag_id):

        # generate the qr code and send it to printer
        qr_url = create_qr(tag_uri(tag_id))
{'fraction_non_alphanumeric': 0.1098579782790309, 'fraction_numerical': 0.0015664160401002505, 'mean_word_length': 2.4724437998549673, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '990856', 'n_tokens_mistral': 2795, 'n_tokens_neox': 2746, 'n_words': 860}