Exemplo n.º 1
0
def edit(sno):

    if request.method == "POST":
        title = request.form.get('k1')
        slug = request.form.get('k2')
        content = request.form.get('k3')
        date = datetime.datetime.now()

        if sno == '0':
            post = Posts(title=title, slug=slug, content=content, date=date)
            db.session.add(post)
            db.session.commit()

        else:
            post = Posts.query.filter_by(sno=sno).first()
            post.title = title
            post.slug = slug
            post.content = content
            db.session.commit()
            return redirect('/edit/' + sno)

    post = Posts.query.filter_by(sno=sno).first()

    if post is None:
        sno = 0

    return render_template('edit.html', post=post, sno=sno)
Exemplo n.º 2
0
def get_posts():
    posts = getattr(g, "posts", None)
    if posts is None:
        posts = g._posts = Posts(app.config["COUCHDB_USER"],
                                 app.config["COUCHDB_PASSWORD"],
                                 app.config["COUCHDB_NAME"])
    return posts
Exemplo n.º 3
0
  def updateFile(self, fileId, http, currentBlog):
    forced = self.request.get('force')
    req = service.files().get(fileId=fileId)
    item = req.execute(http)
    post = Posts.GetPostById(fileId, currentBlog)
    if post and post.postid != fileId:
      logging.error('No post!')
      post = None
    if not 'title' in item and 'modifiedDate' in item and 'exportLinks' in item:
      return self.error(404)
    title = item['title']
    lastmodified = item['modifiedDate']
    if post and post.lastmodified == lastmodified and not forced:
      return Redirect(self, 'No modifcation needed!', '/get?id=%s' % fileId)
    exportLinks = item['exportLinks']
    htmlResp, htmlContent = http.request(exportLinks['text/html'])
    textResp, textContent = http.request(exportLinks['text/plain'])
    if textResp.status != 200 or htmlResp.status != 200:
      return self.error(404)

    htmlContent = unicode(htmlContent, errors='ignore')
    textContent = unicode(textContent, errors='ignore')
    content = contentparser.analyze(textContent, htmlContent)
    text = MarkdownText(content)
    snippet = ''
    pic = '/r/defaults/%d.jpg' % randint(1,3)
    if post:
      post.text = text
      post.lastmodified = lastmodified
    else:
      post = Posts(title=title,
          text=text,
          pic=pic,
          snippet=snippet,
          lastmodified=lastmodified,
          postid=fileId,
          blog=currentBlog.subdomain,
          visible=False)
    post.put()
    Redirect(self, 'Loading page.', '/get?id=%s' % fileId)
Exemplo n.º 4
0
    def publicarPost(self, nick, id_hashtag, contingut_post):
        """
        Metode que registra posts a partir d'un usuari i d'un hashtag, el Doctest no llista usuaris ja que el timestamp no sera mai igual

        >>> i = iTicApp()
        >>> i.publicarPost('Bernat', 'munta', 'bon diaaa' )
        Usuari no creat
        """
        if nick not in list(self.__usuaris):
            print("Usuari no creat")
        else:
            p = Posts(contingut_post, id_hashtag)
            p.registraUsuari(nick)

            if (id_hashtag not in self.__hashtags.keys()):
                print("Hashtag no creat")
                self.__hashtags[id_hashtag] = Hashtag(id_hashtag)
                p.registraHashtag(Hashtag(id_hashtag))
                self.__hashtags[id_hashtag].hashTagUtilitzat()

            else:
                self.__hashtags[id_hashtag].hashTagUtilitzat()

            self.__usuaris[nick].registraPost(p)

            if (nick not in list(self.__posts)):
                self.__posts[nick] = []
                self.__posts[nick].append(p)
            else:
                self.__posts[nick].append(p)
Exemplo n.º 5
0
    def select(cls):
        cursor = Connection.get_cursor()
        logger.debug(cursor.mogrify(cls.__SELECT))
        cursor.execute(cls.__SELECT)
        registers = cursor.fetchall()

        Posts_User = []
        for register in registers:
            post = Posts(register[0], register[1], register[2], register[3],
                         register[4])
            Posts_User.append(post)
        Connection.close()
        return Posts_User
Exemplo n.º 6
0
def index():
    postlist = []
    result = firebase.get('/posts', None)
    for key,value in result.items():
        postlist.append(Posts(key,value).getShowable())
    print(postlist[0])


    error = 'You are not logged in'
    dumb = 'dumb'
    '''if 'username' not in session:
        return redirect(url_for('login',methods=['GET', 'POST']))'''
    return render_template('home.html', error=error, dumb=dumb, posts=postlist)
Exemplo n.º 7
0
 def findPost(self, currentBlog):
   match = re.match('/post/(\d+)/([-a-z0-9]+)', self.request.path)
   if not match:
     match = re.match('/post/([-a-z0-9]+)', self.request.path)
     stitle = match.group(1)
     if stitle:
       return Posts.GetPostBySmallName(stitle, currentBlog)
   else:
     sdate = match.group(1)
     stitle = match.group(2)
     if sdate and stitle:
       return Posts.query(Posts.small_date==sdate,
           Posts.small_name==stitle).get()
   return None
Exemplo n.º 8
0
def profile(id):
    if id=="myself":
        if 'username' not in session:
            print("aaaaaa")
        print(session['username'])
        user = User(firebase.get('/users/' + session['username'], None))
        user.department=Utils.short([user.department])[0]
        return render_template('profile.html',user=user,edit=True)
    user=User(firebase.get('/users/'+id,None))
    postlist = []
    result = firebase.get('/posts', None)
    for key, value in result.items():
        postlist.append(Posts(key, value).getShowable())
    postlist=[post for post in postlist if post.authorId==id]
    return render_template('profile.html',user=user,edit=False,posts=postlist)
Exemplo n.º 9
0
def index():
    posts = Posts('./posts/')
    return render_template("posts.html", start=0, end=5, posts=posts)
Exemplo n.º 10
0
import os
import discord
from misc import *
from posts import Posts

# Initializing reddit and discord clients
client = discord.Client()
imgs = Posts()


def make_meme_embed(post):
    """Makes a meme discord embed

    Args:
        post (submission): reddit submission

    Returns:
        embed: meme embed ready to send
    """
    to_send = discord.Embed(
        title=post.title,
        url=f"https://www.reddit.com/r/{post.subreddit}/comments/{str(post)}",
        description=f"u/{str(post.author)}",
        color=random_color_int(),
    )
    to_send.set_author(
        name=f"r/{str(post.subreddit)}",
        url=f"https://www.reddit.com/r/{post.subreddit}",
        icon_url=post.subreddit.icon_img,
    )
    to_send.set_image(url=post.url)
Exemplo n.º 11
0
    # Get Followers from user id
    client = Followers(cookies=cookies, debug=True)
    followers_profiles = client.get_all_followers_profiles_using_user_id(user_id=124)
    print(followers_profiles)

    # Get Followings from user id
    client = Following(cookies=cookies, debug=True)
    following_profiles = client.get_all_following_profiles_using_user_id(user_id=124)
    print(following_profiles)

    img = urllib.request.urlopen(
        'https://instagram.fbho4-1.fna.fbcdn.net/v/t51.2885-19/s320x320/29093337_228763574365850_5571283674877394944_n.jpg?_nc_ht=instagram.fbho4-1.fna.fbcdn.net&_nc_ohc=8-cgeWsuzGMAX8NhY3k&edm=ABfd0MgBAAAA&ccb=7-4&oh=b2ce5cf8af369e33e51942df0f7bd590&oe=60FB15D5&_nc_sid=7bff83')
    photo = img.read()

    # Post a photo
    client = Posts(cookies=cookies, debug=True)
    post_result = client.post_a_picture(data=photo, caption="testing. Please Ignore")
    print(post_result)

    # Post a story
    client = Posts(cookies=cookies, debug=True)
    story_result = client.post_a_story(data=photo, caption="testing. Please Ignore")
    print(story_result)

    # Get a User Reels
    client = Reels(cookies=cookies, debug=True)
    post_result = client.get_reels_using_user_id(user_id=1301203788)
    print(post_result)
    if post_result['max_id']:
        post_result = client.get_reels_using_user_id(user_id=1301203788, max_id=post_result['max_id'])
        print(post_result)
Exemplo n.º 12
0
Arquivo: tasks.py Projeto: manhg/tokit
def create_tables():
    Posts.create_table()
Exemplo n.º 13
0
def getPostsLanding():
    try:
        result = Posts.fetchPostsLandingJson()
        return Helpers.OK(result)
    except Exception as e:
        return Helpers.ERROR_INTERNAL(e)
Exemplo n.º 14
0
def getPost(postroute):
    try:
        result = Posts.fetchPostJson(postroute)
        return Helpers.OK(result)
    except Exception as e:
        return Helpers.ERROR_INTERNAL(e)
Exemplo n.º 15
0
        return Helpers.OK(result)
    except Exception as e:
        return Helpers.ERROR_INTERNAL(e)


@app.route("/posts/<postroute>", methods=["GET"])
def getPost(postroute):
    try:
        result = Posts.fetchPostJson(postroute)
        return Helpers.OK(result)
    except Exception as e:
        return Helpers.ERROR_INTERNAL(e)


@app.route("/postslanding", methods=["GET"])
def getPostsLanding():
    try:
        result = Posts.fetchPostsLandingJson()
        return Helpers.OK(result)
    except Exception as e:
        return Helpers.ERROR_INTERNAL(e)


if __name__ == "__main__":
    Globals.isDebug = "--debug" in sys.argv
    Posts.fetchPosts()
    if Globals.isDebug:
        app.run(port=4000)
    else:
        app.run(port=8000)
Exemplo n.º 16
0
def post_select(start, end):
    posts = Posts('./posts/')
    return render_template("posts.html", start=start, end=end, posts=posts)
Exemplo n.º 17
0
import requests
import json
from post import Post
from posts import Posts
url = "https://jsonplaceholder.typicode.com/posts"
response = requests.get(url)
json_data = response.text
posts = json.loads(json_data)
#keys=posts[0].keys()
#print(keys)
#create Post objects and append it to objects list
objects = []
for i in posts:
    post = Post(i['id'], i['userId'], i['title'], i['body'])
    objects.append(post)

#create Posts object
postsObject = Posts(objects)
postsObject.showAllPosts()
# needed_posts = postsObject.getPostByUserId(1)
# for i in needed_posts:
#     print(i)
Exemplo n.º 18
0
    def test_json(self):
        p = Posts('Test', 'Test Content')
        expected = {'title': 'Test', 'content': 'Test Content'}

        self.assertDictEqual(expected, p.json())
Exemplo n.º 19
0
            bestmatch = target['bestmatch']
            reportmessage = f"""{{report: {{ reason: "false-positive", id: "{id}" }}}}"""
            fplink = f'https://www.reddit.com/message/compose?to=/r/darkrepostbot&subject=False-positive&message=' + reportmessage
            reply = shortreplystr.format(bestmatch['match'], bestmatch['url'],
                                         len(ps.posts), fplink)
            log('Replying:\n' + reply)
            target['commentId'] = comment(reply, reddit.submission(id=id))
            plog.posts['reposts'].append(target)
        for i, post in enumerate(plog.posts['processedposts']):
            if urltoId(post['url']) == id:
                plog.posts['processedposts'][i] = target
        return 200


ErrLog.load()
ps = Posts(sub)
st = Stats(statspost, statstr)
plog = ProcessedLogger()
Server.start(port=port,
             repfalsepos=ServerEventHandler.ReportFalsePositive,
             revpotrep=ServerEventHandler.ReviewPotentaialRepost)


def refresh():
    logp('Started refresh thread')
    while True:
        time.sleep(1850)
        try:
            reddit = praw.Reddit(client_id=client_id,
                                 client_secret=secret,
                                 password=password,
Exemplo n.º 20
0
 def test_create_posts(self):
     p = Posts('Test', 'Test Content')
     self.assertEqual('Test', p.title)
     self.assertEqual('Test Content', p.content)