Beispiel #1
0
def getConn(DB):
    global DSN
    if DSN is None:
        DSN = dbi.read_cnf()
    conn = dbi.connect(DSN)
    conn.select_db(DB)
    return conn
Beispiel #2
0
def getConn(db):
    # this line is to allow db connection on a personal account
    # dsn = dbi.read_cnf("~/.textbook.cnf")
    dsn = dbi.read_cnf()
    conn = dbi.connect(dsn)
    dbi.select_db(conn, db)
    return conn
def newsSource(nsid):
    conn = dbi.connect('credbase')
    source = dbi.lookupNewsSource(conn, nsid)
        
    if source == None:
        flash("Sorry, no news source with this ID is in the database")
        return redirect( url_for('home') )
    else:
        if 'username' in session and dbi.checkInWatchlist(conn, nsid, session['username']) is not None:
            source['onWatchlist'] = True
        else:
            source['onWatchlist'] = False
        stories = dbi.getStoriesByNewsSource(conn, nsid)
        similar = dbi.getSimilar(conn, nsid)
        #handle error that sometimes occurs, with unicode (some titles and URLs have hex characters in them)
        try:
            for story in stories:
                story['url'] = unicode(story['url'], errors='ignore')
                story['title'] = unicode(story['url'], errors='ignore')
                story['originQuery'] = unicode(story['originQuery'], errors='ignore')
                story['resultDate'] = unicode(story['resultDate'], errors='ignore')
            return render_template('news_source_page.html', page_title=unicode(source['name'], errors='ignore'), newsSource=source, stories=stories, similar_sources=similar, login_session=session)
        #sometimes have errors turning into unicode if already converted
        except TypeError: 
            return render_template('news_source_page.html', page_title=source['name'], newsSource=source, stories=stories, similar_sources=similar, login_session=session)
def searchNewsSources(search_term):
    """This page displays search results when there are multiple results that
    satisfy the search query. If there is only one, it redirects to the page
    of this news source. If there are none, it flashes the message"""
    conn = dbi.connect('credbase')
    search_results = dbi.getSearchedNewsSources(conn, search_term)
    
    #list of source nsid's that the current user is watching
    if 'username' in session:
        watched_sources = dbi.getWatchedNewsSources(conn, session['username'])
        nsid_lst = [source['nsid'] for source in watched_sources]
    else:
        nsid_lst = []
    
    for entry in search_results:
        print entry['name']
        entry['name'] = unicode(entry['name'], errors='ignore')
        #sources that are on the watchlist are tagged
        if entry['nsid'] in nsid_lst:
            entry['onWatchlist'] = True
        else:
            entry['onWatchlist'] = None
        
    if len(search_results) == 1:
        return redirect(url_for('newsSource', nsid=search_results[0]['nsid']))
    elif len(search_results) == 0:
        flash('Sorry, no news source with such name was found')
    return render_template('searched_sources_page.html', page_title="Search results for: '" + search_term + "'", search_results=search_results, login_session=session)
def addSource():
    if 'username' not in session:
        flash("You must be logged in to use this feature")
        return render_template("home_page.html", page_title="Welcome to CRED base!", login_session=session)
    conn = dbi.connect('credbase') 
    if request.method == "GET":
        return render_template('add_source.html', login_session=session)
    else:
        if 'submitSourceAdd' in request.form:
            print request.form
            if 'add' in request.form['submitSourceAdd']:
                name = request.form.get('name')
                print name
                if name != "":
                    publisher = request.form.get('publisher')
                    mediatype = request.form.get('mediatype')
                    location = request.form.get('location')
                    editor = request.form.get('editor')
                    url = request.form.get('url')
                    doe = request.form.get('doe')
                    dbi.addNewsSource(conn, name, publisher, mediatype, location, editor, url, doe)
                    flash("New news source " + name + " was successfully added.")
                    return render_template('add_source.html',login_session=session)
                else:
                    flash("Your source must have a name")
                    return render_template('add_source.html',login_session=session)
Beispiel #6
0
def login():
    try:
        username = request.form['username']
        passwd = request.form['password']
        conn = dbi.connect('credbase')
        result = dbi.checkUserPass(conn, username)
        
        if result is None:
            # Same response as wrong password, so no information about what went wrong
            flash('login incorrect. Try again or join')
            return redirect( url_for('home'))
            
        hashed = result['hashedPWD']
        name = result['name']
        # strings always come out of the database as unicode objects
        
        if bcrypt.hashpw(passwd.encode('utf-8'),hashed.encode('utf-8')) == hashed:
            flash('successfully logged in as '+username)
            session['username'] = username
            session['name'] = name
            return redirect( url_for('user', username=username) )
        else:
            flash('login incorrect. Try again or join')
            return redirect( url_for('home'))
    except Exception as err:
        flash('form submission error '+str(err))
        return redirect( url_for('home') )
Beispiel #7
0
def join():
    try:
        name = request.form['name']
        username = request.form['username']
        passwd1 = request.form['password1']
        passwd2 = request.form['password2']
        if passwd1 != passwd2:
            flash('passwords do not match')
            return redirect( url_for('home'))
        hashed = bcrypt.hashpw(passwd1.encode('utf-8'), bcrypt.gensalt())
        conn = dbi.connect('credbase')
        result = dbi.checkUserPass(conn, username)
        
        #NEED TO ADD THREAD SAFE MODIFICATIONS HERE
        if result is not None:
            #WE COULD USE AJAX HERE
            flash('That username is taken')
            return redirect(url_for('home'))
        else:
            #adds a new username into the system
            dbi.addUser(conn, name, username, hashed)
        
        session['username'] = username
        session['name'] = name
        return redirect( url_for('user', username=username) )
    except Exception as err:
        flash('form submission error '+str(err))
        return redirect( url_for('home') )
def join():
    try:
        name = request.form['name']
        username = request.form['username']
        passwd1 = request.form['password1']
        passwd2 = request.form['password2']
        if not username.isalnum():
            flash('username should be alphanumeric')
            return redirect( url_for('home'))
        if passwd1 != passwd2:
            flash('passwords do not match')
            return redirect( url_for('home'))
        hashed = bcrypt.hashpw(passwd1.encode('utf-8'), bcrypt.gensalt())
        conn = dbi.connect('credbase')
        #tries adding a new username into the system
        result = dbi.addUser(conn, name, username, hashed)
        
        if not result:
            flash('This username is taken')
            return redirect(url_for('home'))
        
        session['username'] = username
        session['name'] = name
        return redirect( url_for('user', username=username) )
    except Exception as err:
        flash('form submission error '+str(err))
        return redirect( url_for('home') )
Beispiel #9
0
def getTups():
    outF = open("MBFC_all.txt", "w")

    conn = dbi.connect('credbase')
    #substitute for NSID
    count = 0
    for entry in data:
        name = "'" + entry['name'].encode('utf-8') + "'"
        publisher = "NULL"
        mediatype = "NULL"
        location = "NULL"
        editor = "NULL"
        if entry['external_url'] != None:
            url = "'" + entry['external_url'].encode('utf-8') + "'"
        else:
            url = "NULL"
        doe = "NULL"
        if entry != data[-1]:
            tup = "(" + "NULL" + ", " + unicode(
                name, errors='ignore') + ", " + str(publisher) + ", " + str(
                    mediatype) + ", " + str(location) + ", " + str(
                        editor) + ", " + unicode(
                            url, errors='ignore') + ", " + str(doe) + "), "
        else:
            tup = "(" + "NULL" + ", " + unicode(
                name, errors='ignore') + ", " + str(publisher) + ", " + str(
                    mediatype) + ", " + str(location) + ", " + str(
                        editor) + ", " + unicode(
                            url, errors='ignore') + ", " + str(doe) + ")"
        outF.write(tup)
        #dbi.addNewsSource(conn, name, publisher, mediatype, location, editor, url, doe)
        count += 1
        #tuplist.append(tup)
        #[count, name, publisher, mediatype, location, editor, url, doe])
    outF.close()
Beispiel #10
0
def getConn(db):
    '''returns a database connection to the given database'''
    global DSN
    if DSN is None:
        DSN = dbi.read_cnf()
    conn = dbi.connect(DSN)
    conn.select_db(db)
    return conn
def unwatchSource():
    if 'username' not in session:
        flash("You must be logged in to use this feature")
        return render_template("home_page.html", page_title="Welcome to CRED base!", login_session=session)
    
    username = session['username']
    nsid = request.form['nsid']
    conn = dbi.connect('credbase')
    dbi.removeFromWatchlist(conn, nsid, username)
    return jsonify({'nsid':nsid})
def file_upload():
    print session
    #check that user is logged in
    if 'username' not in session:
        flash("You must be logged in to use this feature")
        return render_template("home_page.html", page_title="Welcome to CRED base!", login_session=session)
    #if method is GET, just render the empty page
    if request.method == 'GET':
        return render_template('upload_json.html',src='',nm='', login_session=session)
    else:
        #catch any upload errors
        try:
            #check Cred PIN, which is stored encrypted in users table associated with credAdmin account
            pin = request.form['nm']
            conn = dbi.connect('credbase')
            result = dbi.checkUserPass(conn, 'credAdmin')
            hashed = result['hashedPWD']
            if bcrypt.hashpw(pin.encode('utf-8'),hashed.encode('utf-8')) != hashed:
                flash('PIN that you entered is incorrect')
                return render_template('upload_json.html',src='',nm='', login_session=session)
            
            #proceed with upload
            nm = session['username']
            query = request.form['query']
            date = request.form['date']
            #make uploader give a valid date and query for use in database
            if query == '' or date == '':
                if query == '':
                    flash('You must provide the query title')
                if date == '':
                    flash('You must provide a date in format month-day-year, ex: 01-01-2018')
                return render_template('upload_json.html',src='',nm='', login_session=session)
            f = request.files['file']
            #check to see if file is indeed a JSON file, just checks extension
            validJSON = False 
            if f.content_type == "application/json":
                validJSON = True
            else:
                flash("Upload Error: file must be of type JSON")
            if validJSON:
                filename = secure_filename('{}_{}.{}'.format(nm, query, "json"))
                pathname = os.path.join(app.config['UPLOADS'],filename)
                f.save(pathname)
                flash('Upload successful')
                dbi.addFile(conn, nm, filename, query, date)
                return render_template('upload_json.html',
                                       nm=filename, login_session=session)
            return render_template('upload_json.html',src='',nm='', login_session=session)
        except Exception as err:
            flash('Upload failed {why}'.format(why=err))
            return render_template('upload_json.html',src='',nm='', login_session=session)
def searchArticles():
    '''Redirects to the page with article titles whose title is like the query'''
    if request.method == "POST":
        conn = dbi.connect('credbase')
        title = request.form.get("query-term")
        articles = dbi.findArticlesByTopic(conn, title)
        for entry in articles:
            print entry
            entry['url'] = entry['url'].decode('utf-8')
            entry['title'] = entry['title'].decode('utf-8')
            entry['name'] = entry['name'].decode('utf-8')
        return render_template('search_by_query.html', articles=articles)
    else:
        return render_template('search_by_query.html', articles=[])
Beispiel #14
0
 def Connect(self):
     self.db = dbi.connect(
         self._host, self._port, self._socket, self._user, self._passwd, self._database)
     # MySQL 5.5+ will say it's unsafe, really it isn't because
     # we specify values only for one unique key
     warnings.filterwarnings('ignore', 'Unsafe statement written to the binary log')
     cursor = self.db.cursor()
     cursor.execute("SET AUTOCOMMIT=1")
     table_list = self.GetTableList()
     if 'metadata' in table_list:
         version = self.GetMetadataValue("version")
         if version is None:
             self._version = 0
         else:
             self._version = int(version)
     else:
         self._version = 0
     if self._version > CURRENT_SCHEMA_VERSION:
         raise DatabaseVersionError("Database version %d is newer than the "
                                    "last version supported by this "
                                    "software." % (self._version))
     if self.index_content:
         self.sphinx = dbi.connect(self.sphinx_host, self.sphinx_port, self.sphinx_socket, '', '', '')
def watchSource():
    if 'username' not in session:
        flash("You must be logged in to use this feature")
        return render_template("home_page.html", page_title="Welcome to CRED base!", login_session=session)
    
    username = session['username']
    nsid = request.form['nsid']
    conn = dbi.connect('credbase')
    if dbi.addToWatchlist(conn, nsid, username):
        return jsonify({'nsid':nsid})
    else:
        flash("You are already watching this source")
        # return redirect(request.referrer)
        return redirect( url_for('home'))
Beispiel #16
0
def searchNewsSources(search_term):
    """This page displays search results when there are multiple results that
    satisfy the search query. If there is only one, it redirects to the page
    of this news source. If there are none, it flashes the message"""
    conn = dbi.connect('credbase')
    search_results = dbi.getSearchedNewsSources(conn, search_term)
    for entry in search_results:
        print entry['name']
        entry['name'] = unicode(entry['name'], errors='ignore')
        
    if len(search_results) == 1:
        return redirect(url_for('newsSource', nsid=search_results[0]['nsid']))
    elif len(search_results) == 0:
        flash('Sorry, no news source with such name was found')
    return render_template('searched_sources_page.html', page_title="Search results for: '" + search_term + "'", search_results=search_results, login_session=session.get('name', 'Not logged in'))
Beispiel #17
0
def addSource():
    #NOT THREAD SAFE -- NEED TO FIX (should be fixed, ARR 11/11)
    if 'username' not in session:
        flash("You must be logged in to use this feature")
        return render_template("home_page.html", page_title="Welcome to CRED base!", login_session=session.get('name', 'Not logged in'))
    conn = dbi.connect('credbase') 
    if request.method == "GET":
        return render_template('add_source.html', login_session=session.get('name', 'Not logged in'))
    else:
        if 'submitSourceAdd' in request.form:
            print request.form
            if 'add' in request.form['submitSourceAdd']:
                #ARR: this is ugly code, might be a better way to check for None values...
                #I'll keep pondering 
                if request.form['name'] == "":
                    #only mandatory information for a source is a name
                    flash("Your source must have a name")
                    return render_template('add_source.html',login_session=session.get('name', 'Not logged in'))
                else:
                    name = request.form['name']
                if request.form['publisher'] == "":
                    publisher = None
                else:
                    publisher = request.form['publisher']
                #have to handle mediatype specially bc radio button
                if 'mediatype' not in request.form['submitSourceAdd']:
                    mediatype = None
                else:
                    mediatype = request.form['mediatype']
                if request.form['location'] == "":
                    location = None
                else:
                    location = request.form['location']
                if request.form['editor'] == "":
                    editor = None
                else:
                    editor = request.form['editor']
                if request.form['url'] == "":
                    url = None
                else:
                    url = request.form['url']
                if request.form['doe'] == "":
                    doe = None
                else:
                    doe = request.form['doe']
                dbi.addNewsSource(conn, name, publisher, mediatype, location, editor, url, doe)
                flash("New news source " + name + " was successfully added.")
                return render_template('add_source.html',login_session=session.get('name', 'Not logged in'))
Beispiel #18
0
def searchArticles(search_term):
    '''This page displays article titles whose title is like the query'''
    conn = dbi.connect('credbase') 
    print "search term: " + search_term
    articles = dbi.findArticlesByTopic(conn, search_term)
    try:
        for entry in articles:
            print entry
            entry['url'] = unicode(entry['url'], errors='ignore')
            entry['title'] = unicode(entry['title'], errors='ignore')
            entry['name'] = unicode(entry['name'], errors='ignore')
            print entry['name']
        return render_template('search_by_query.html', articles=articles, login_session=session.get('name', 'Not logged in'))
    #don't know why error happens but it does and we handle it here
    except TypeError: 
        return render_template('search_by_query.html', articles=articles, login_session=session.get('name', 'Not logged in'))
Beispiel #19
0
def updateArticle(sid):
    #NOT THREAD SAFE -- NEED TO FIX (should be fixed now - ARR 11/11)
    if 'username' not in session:
        flash("You must be logged in to use this feature")
        return render_template("home_page.html", page_title="Welcome to CRED base!", login_session=session.get('name', 'Not logged in'))
    
    conn = dbi.connect('credbase') 
    if request.method == "GET":
        articleInfo = dbi.getArticleBySid(conn, sid)
        #handling case of hex characters in titles and URLs
        try:
            articleInfo['url'] = unicode(articleInfo['url'], errors='ignore')
            articleInfo['title'] = unicode(articleInfo['title'], errors='ignore')
            return render_template('update_article.html', articleInfo=articleInfo, login_session=session.get('name', 'Not logged in'))
        #handle case where already converted
        except TypeError:
            return render_template('update_article.html', articleInfo=articleInfo, login_session=session.get('name', 'Not logged in'))
    if request.method == "POST":
        #if user wants to delete the article 
        if 'submitDelete' in request.form:
            if 'delete' in request.form['submitDelete']: 
                print "going to delete"
                dbi.deleteSearchResult(conn, sid)
                flash("Article with SID: " + str(sid) + " was removed from the database")
                articleInfo = dbi.getArticleBySid(conn, sid)
                return render_template('update_article.html', articleInfo=[], login_session=session.get('name', 'Not logged in'))
        #if user wants to update elements of the article's entry
        if 'submitUpdate' in request.form:
            if 'update' in request.form['submitUpdate']: 
                original = dbi.getArticleBySid(conn, sid)
                #check to see that original and current values don't match before updating
                if (original['url'] != request.form['url']) and (request.form['url'] != ""):
                    dbi.updateArticleURL(conn, request.form['url'], sid)
                if (original['resultDate'] != request.form['date']) and (request.form['date'] != ""):
                    print "updating result date: " + str(request.form['date'])
                    dbi.updateArticleResultDate(conn, request.form['date'], sid)
                if (original['originQuery'] != request.form['oq']) and (request.form['oq'] != ""):
                    dbi.updateArticleOriginQuery(conn, request.form['oq'], sid)
                if (original['title'] != request.form['title']) and (request.form['title'] != ""):
                     dbi.updateArticleTitle(conn, request.form['title'], sid)
                articleInfo = dbi.getArticleBySid(conn, sid)
                return render_template('update_article.html', articleInfo=articleInfo, login_session=session.get('name', 'Not logged in'))
    articleInfo = dbi.getArticleBySid(conn, sid)
    flash("No changes made, please change appropriate values or delete item, as desired")
    return render_template('update_article.html', articleInfo=articleInfo, login_session=session.get('name', 'Not logged in'))
 def Connect(self):
     self.db = dbi.connect(
         self._host, self._port, self._user, self._passwd, self._database)
     cursor = self.db.cursor()
     cursor.execute("SET AUTOCOMMIT=1")
     table_list = self.GetTableList()
     if 'metadata' in table_list:
         version = self.GetMetadataValue("version")
         if version is None:
             self._version = 0
         else:
             self._version = int(version)
     else:
         self._version = 0
     if self._version > CURRENT_SCHEMA_VERSION:
         raise DatabaseVersionError("Database version %d is newer than the "
                                    "last version supported by this "
                                    "software." % (self._version))
Beispiel #21
0
 def Connect(self):
     self.db = dbi.connect(
         self._host, self._port, self._user, self._passwd, self._database)
     cursor = self.db.cursor()
     cursor.execute("SET AUTOCOMMIT=1")
     table_list = self.GetTableList()
     if 'metadata' in table_list:
         version = self.GetMetadataValue("version")
         if version is None:
             self._version = 0
         else:
             self._version = int(version)
     else:
         self._version = 0
     if self._version > CURRENT_SCHEMA_VERSION:
         raise DatabaseVersionError("Database version %d is newer than the "
                                    "last version supported by this "
                                    "software." % (self._version))
Beispiel #22
0
def file_upload():
    print session
    #check that user is logged in
    if 'username' not in session:
        flash("You must be logged in to use this feature")
        return render_template("home_page.html", page_title="Welcome to CRED base!", login_session=session.get('name', 'Not logged in'))
    #if method is GET, just render the empty page
    if request.method == 'GET':
        return render_template('upload_json.html',src='',nm='', login_session=session.get('name', 'Not logged in'))
    else:
        #catch any upload errors
        try:
            #gets CRED-ID
            nm = int(request.form['nm']) # may throw error
            query = request.form['query']
            date = request.form['date']
            #make uploader give a valid date and query for use in database
            if query == '' or date == '':
                if query == '':
                    flash('You must provide the query title')
                if date == '':
                    flash('You must provide a date in format month-day-year, ex: 01-01-2018')
                return render_template('upload_json.html',src='',nm='', login_session=session.get('name', 'Not logged in'))
            f = request.files['file']
            #check to see if file is indeed a JSON file, just checks extension
            validJSON = False 
            if f.content_type == "application/json":
                validJSON = True
            else:
                flash("Upload Error: file must be of type JSON")
            if validJSON:
                filename = secure_filename('{}{}.{}'.format(nm, query, "json"))
                pathname = os.path.join(app.config['UPLOADS'],filename)
                f.save(pathname)
                flash('Upload successful')
                conn = dbi.connect('credbase')
                dbi.addFile(conn, nm, filename, query, date)
                return render_template('upload_json.html',
                                       nm=filename, login_session=session.get('name', 'Not logged in'))
            return render_template('upload_json.html',src='',nm='', login_session=session.get('name', 'Not logged in'))
        except Exception as err:
            flash('Upload failed {why}'.format(why=err))
            return render_template('upload_json.html',src='',nm='', login_session=session.get('name', 'Not logged in'))
def user(username):
    try:
        # don't trust the URL; it's only there for decoration
        if 'username' in session:
            username = session['username']
            conn = dbi.connect('credbase')
            user_info = dbi.lookupUser(conn, username)
            sources = dbi.getWatchedNewsSources(conn, username)
            return render_template('user_page.html',
                                   page_title=user_info['name'],
                                   sources=sources,
                                   login_session=session.get(
                                       'name', 'Not logged in'))
        else:
            flash('you are not logged in. Please login or join')
            return redirect(url_for('home'))
    except Exception as err:
        flash('some kind of error ' + str(err))
        return redirect(url_for('home'))
def file_upload():
    if request.method == 'GET':
        return render_template('upload_json.html', src='', nm='')
    else:
        try:
            nm = int(request.form['nm'])  # may throw error
            query = request.form['query']
            date = request.form['date']
            #make uploader give a valid date and query for use in database
            if query == '' or date == '':
                if query == '':
                    flash('You must provide the query title')
                if date == '':
                    flash(
                        'You must provide a date in format month-day-year, ex: 01-01-2018'
                    )
                return render_template('upload_json.html', src='', nm='')
            f = request.files['file']
            validJSON = False
            # weak check to see if file is true json file
            if f.content_type == "application/json":
                validJSON = True
            else:
                flash("Upload Error: file must be of type JSON")
            if validJSON:
                filename = secure_filename('{}.{}'.format(nm, "json"))
                print "filename: " + filename
                pathname = os.path.join(app.config['UPLOADS'], filename)
                print "pathname: " + pathname
                f.save(pathname)
                print "saved file"
                flash('Upload successful')
                conn = dbi.connect('credbase')
                curs = conn.cursor()
                dbi.addFile(conn, nm, filename, query, date)
                return render_template('upload_json.html',
                                       src=url_for('file_upload', nm=nm),
                                       nm=nm)
            return render_template('upload_json.html', src='', nm='')
        except Exception as err:
            flash('Upload failed {why}'.format(why=err))
            return render_template('upload_json.html', src='', nm='')
Beispiel #25
0
def user(username):
    try:
        # don't trust the URL; it's only there for decoration
        if 'username' in session:
            user = session['username']
            if username != user:
                flash('You are not logged in as this account. Switch accounts to proceed')
                return redirect( url_for('home') )
            conn = dbi.connect('credbase')
            user_info = dbi.lookupUser(conn, user)
            sources = dbi.getWatchedNewsSources(conn, user)
            for source in sources:
                source['name'] = dbi.lookupNewsSource(conn, source['nsid'])['name']
            return render_template('user_page.html', page_title=user_info['name'], sources=sources, login_session=session.get('name', 'Not logged in'))
        else:
            flash('You are not logged in. Please login or join')
            return redirect( url_for('home') )
    except Exception as err:
        flash('Error: '+str(err))
        return redirect( url_for('home') )
def newsSource(nsid):
    conn = dbi.connect('credbase')
    source = dbi.lookupNewsSource(conn, nsid)
    if source == None:
        flash("Sorry, no news source with this ID is in the database")
        #We need to create not found page or something...
        return redirect(url_for('home'))
    else:
        stories = dbi.getStoriesByNewsSource(conn, nsid)
        for story in stories:
            print story
            story['url'] = story['url'].decode('utf-8')
            story['title'] = story['title'].decode('utf-8')
            story['originQuery'] = story['originQuery'].decode('utf-8')
        return render_template('news_source_page.html',
                               page_title=source['name'],
                               newsSource=source,
                               stories=stories,
                               login_session=session.get(
                                   'name', 'Not logged in'))
Beispiel #27
0
def newsSource(nsid):
    conn = dbi.connect('credbase')
    source = dbi.lookupNewsSource(conn, nsid)
    if source == None:
        flash("Sorry, no news source with this ID is in the database")
        #We need to create not found page or something...
        return redirect( url_for('home') )
    else:
        stories = dbi.getStoriesByNewsSource(conn, nsid)
        #handle error that sometimes occurs, with unicode (some titles and URLs have hex characters in them)
        try:
            for story in stories:
                story['url'] = unicode(story['url'], errors='ignore')
                story['title'] = unicode(story['url'], errors='ignore')
                story['originQuery'] = unicode(story['originQuery'], errors='ignore')
                story['resultDate'] = unicode(story['resultDate'], errors='ignore')
            return render_template('news_source_page.html', page_title=unicode(source['name'], errors='ignore'), newsSource=source, stories=stories, login_session=session.get('name', 'Not logged in'))
        #sometimes have errors turning into unicode if already converted
        except TypeError: 
            return render_template('news_source_page.html', page_title=source['name'], newsSource=source, stories=stories, login_session=session.get('name', 'Not logged in'))
Beispiel #28
0
 def Connect(self):
     self.db = dbi.connect(
         self._host, self._port, self._user, self._passwd, self._database)
     cursor = self.db.cursor()
     cursor.execute("SET AUTOCOMMIT=1")
Beispiel #29
0
def getConn(db):
    '''Returns a database connection for that db'''
    dsn = dbi.read_cnf()
    conn = dbi.connect(dsn)
    conn.select_db(db)
    return conn
Beispiel #30
0
def updateSource(nsid):
    #NOT THREAD SAFE -- NEED TO FIX (should be fixed, ARR 11/11)
    if 'username' not in session:
        flash("You must be logged in to use this feature")
        return render_template("home_page.html", page_title="Welcome to CRED base!", login_session=session.get('name', 'Not logged in'))

    conn = dbi.connect('credbase') 
    if request.method == "GET":
        sourceInfo = dbi.lookupNewsSource(conn, nsid)
        #handing hex characters
        try:
            sourceInfo['url'] = unicode(sourceInfo['url'], errors='ignore')
            sourceInfo['name'] = unicode(sourceInfo['name'], errors='ignore')
            return render_template('update_source.html', sourceInfo=sourceInfo, login_session=session.get('name', 'Not logged in'))
        except TypeError:
            return render_template('update_source.html', sourceInfo=sourceInfo, login_session=session.get('name', 'Not logged in'))
    if request.method == "POST":
        print "got inside post"
        #delete if user wants
        if len(request.form) != 0:
            if 'submitDelete' in request.form:
                if 'delete' in request.form['submitDelete']: 
                    print "going to delete"
                    dbi.deleteSource(conn, nsid)
                    flash("Source with NSID: " + str(nsid) + " was removed from the database")
                    sourceInfo = dbi.lookupNewsSource(conn, nsid)
                    return render_template('update_source.html', sourceInfo=[], login_session=session.get('name', 'Not logged in'))
            #otherwise update as appropriate
            if 'submitUpdate' in request.form:
                if 'update' in request.form['submitUpdate']: 
                    original = dbi.lookupNewsSource(conn, nsid)
                    print original
                    if (original['name'] != request.form['name']) and (request.form['name'] != ""):
                         dbi.updateSourceName(conn, request.form['name'], nsid)
                    if (original['publisher'] != request.form['publisher']) and (request.form['publisher'] != ""):
                         dbi.updateSourcePublisher(conn, request.form['publisher'], nsid)
                    #special case where may not have a mediatype value picked
                    if 'mediatype' in request.form:
                        if (original['mediatype'] != request.form['mediatype']) and (request.form['mediatype'] != ""):
                             print original['mediatype']
                             print request.form['mediatype']
                             dbi.updateSourceMediatype(conn, request.form['mediatype'], nsid)
                    if (original['location'] != request.form['location']) and (request.form['location'] != ""):
                         dbi.updateSourceLocation(conn, request.form['location'], nsid)
                    if (original['editor'] != request.form['editor']) and (request.form['editor'] != ""):
                         dbi.updateSourceEditor(conn, request.form['editor'], nsid)
                    if (original['url'] != request.form['url']) and (request.form['url'] != ""):
                        dbi.updateSourceURL(conn, request.form['url'], nsid)
                    if (original['doe'] != request.form['doe']) and (request.form['doe'] != ""):
                         dbi.updateSourceDOE(conn, request.form['doe'], nsid)
                    sourceInfo = dbi.lookupNewsSource(conn, nsid)
                    return render_template('update_source.html', sourceInfo=sourceInfo, login_session=session.get('name', 'Not logged in'))
        
        else:
            print "got into else"
            print dbi.lookupNewsSource(conn, nsid)
            sourceInfo = dbi.lookupNewsSource(conn, nsid)
            try:
                sourceInfo['url'] = unicode(sourceInfo['url'], errors='ignore')
                sourceInfo['name'] = unicode(sourceInfo['name'], errors='ignore')
                return render_template('update_source.html', sourceInfo=sourceInfo, login_session=session.get('name', 'Not logged in'))
            except TypeError:
                return render_template('update_source.html', sourceInfo=sourceInfo, login_session=session.get('name', 'Not logged in'))
    flash("No changes made, please change appropriate values or delete item, as desired")
    return render_template('update_source.html', sourceInfo=sourceInfo, login_session=session.get('name', 'Not logged in'))
Beispiel #31
0
        pass
print("----")

#dbh = dbi.connect("dbi:NullP:")

#$dbh = DBI->connect("DBI:mysql:database=fotodb", "gisle", "",
#                    {
#                      RaiseError => 1,
#                      PrintError => 0,
#                      AutoCommit => 1,
#                    }) || die;

dbh = dbi.connect(
    "DBI:mysql:database=fotodb",
    "gisle",
    RaiseError=1,
    PrintError=0,
    AutoCommit=1,
)

try:
    dbh["AutoCommit"] = 0
except:
    print("Can't turn off AutoCommit")

sth = dbh.prepare("select * from img limit 5")
rows = sth.execute()
print(rows)

while 1:
    row = sth.fetchrow_tuple()
Beispiel #32
0
			print "  ", s
	except:
		pass
print "----"

#$dbh = DBI->connect("DBI:mysql:database=test", "snake", "",
#                    {
#                      RaiseError => 1,
#                      PrintError => 0,
#                      AutoCommit => 1,
#                    }) || die;


dbh = dbi.connect("DBI:mysql:database=test", "snake",
		  RaiseError = 1,
		  PrintError = 0,
		  AutoCommit = 1,
	         )

try:
    dbh["AutoCommit"] = 0
except:
    print "Can't turn off AutoCommit"

sth = dbh.prepare("select * from img limit 5")
rows = sth.execute()
print rows

while 1:
	row = sth.fetchrow_tuple()
        if not row: break
Beispiel #33
0
		pass
print "----"

#dbh = dbi.connect("dbi:NullP:")

#$dbh = DBI->connect("DBI:mysql:database=fotodb", "gisle", "",
#                    {
#                      RaiseError => 1,
#                      PrintError => 0,
#                      AutoCommit => 1,
#                    }) || die;


dbh = dbi.connect("DBI:mysql:database=fotodb", "gisle",
		  RaiseError = 1,
		  PrintError = 0,
		  AutoCommit = 1,
	         )

try:
    dbh["AutoCommit"] = 0
except:
    print "Can't turn off AutoCommit"

sth = dbh.prepare("select * from img limit 5")
rows = sth.execute()
print rows

while 1:
	row = sth.fetchrow_tuple()
        if not row: break
Beispiel #34
0
 def Connect(self):
     self.db = dbi.connect(
         self._host, self._port, self._user, self._passwd, self._database)