示例#1
0
async def on_message(msg):
    '''Do all handling related to checking for messages'''
    if msg.channel.category_id == ROLEPLAY_CHANNELS_CATEGORY:
        # Count!
        db = get_database("leaderboard", msg.guild.id)
        q.record_message(db, msg)
    # Do other command processing too
    await client.process_commands(msg)
示例#2
0
def test_delete_local_by_id():
	shutil.copy(constants.kExampleImageFile, constants.kExampleTemporaryImageFile)
	assert os.path.exists(constants.kExampleTemporaryImageFile)
	database = db.get_database()
	ops = PerceptOps(kConfig)
	with database.get_session() as session:
		percept = session.query(rigor.types.Percept).get(642924)
		percept.locator = 'file://' + constants.kExampleTemporaryImageFile
		ops.destroy(percept.id, session)
	assert not os.path.exists(constants.kExampleTemporaryImageFile)
示例#3
0
文件: cron.py 项目: rutaq/asm3
def run_alias(mode, alias):
    dbo = db.get_database(alias)
    dbo.alias = alias
    if dbo.database == "FAIL":
        print("Invalid database alias '%s'" % (alias))
        return
    else:
        dbo.timeout = 0
        dbo.connection = dbo.connect()
        run(dbo, mode)
示例#4
0
async def list_scenes(ctx):
    db = get_database("scene", ctx.message.guild.id)
    info = q.list_channels(db)
    output = []
    for name, scene_name in info:
        name = "#" + name[:7]
        scene_name = '"' + scene_name[:30] + '"' if scene_name is not None else "Open!"
        output.append(f'{name.rjust(8)}: {scene_name}')
    output = "\n".join(output)
    await ctx.send(f"```\n{output}\n```")
示例#5
0
 def setUp (self):
     print 'Calling setUp'
     # Remove all plugins for testing purposes
     from gourmet.plugin_loader import get_master_loader
     ml = get_master_loader()
     ml.save_active_plugins = lambda *args: True; # Don't save anything we do to plugins
     ml.active_plugins = []
     ml.active_plugin_sets = []
     # Done knocking out plugins...
     tmpfile = tempfile.mktemp()
     self.db = db.get_database(file=tmpfile)
示例#6
0
def test_delete_local():
    shutil.copy(constants.kExampleImageFile,
                constants.kExampleTemporaryImageFile)
    assert os.path.exists(constants.kExampleTemporaryImageFile)
    database = db.get_database()
    ops = PerceptOps(kConfig)
    with database.get_session() as session:
        percept = session.query(rigor.types.Percept).get(642924)
        percept.locator = 'file://' + constants.kExampleTemporaryImageFile
        ops.destroy(percept, session)
    assert not os.path.exists(constants.kExampleTemporaryImageFile)
示例#7
0
 def setUp(self):
     print 'Calling setUp'
     # Remove all plugins for testing purposes
     from gourmet.plugin_loader import get_master_loader
     ml = get_master_loader()
     ml.save_active_plugins = lambda *args: True
     # Don't save anything we do to plugins
     ml.active_plugins = []
     ml.active_plugin_sets = []
     # Done knocking out plugins...
     tmpfile = tempfile.mktemp()
     self.db = db.get_database(file=tmpfile)
示例#8
0
def into_leaderboard(ctx, before=None, after=None, limit=None):
    board = q.count_messages(get_database("leaderboard", ctx.guild.id),
                             before=before,
                             after=after,
                             limit=limit)
    board = [(ctx.guild.get_member(author_id).display_name, count)
             for author_id, count in board]
    board = [f'    {"Name".center(16, "-")}  Posts'] + [
        f'{str(i).rjust(2)}. {t[0][:16].rjust(16)}     {str(t[1]).rjust(2)}'
        for i, t in enumerate(board, 1)
    ]
    return "```" + "\n".join(board) + "```"
示例#9
0
async def end_scene(ctx, *args):
    # Message is deleted first
    await ctx.message.delete()

    db = get_database("scene", ctx.message.guild.id)
    info = q.get_channel_info(db, ctx.message.channel.id)
    # It has to be a channel that is an RP channel & in use
    if info is None or info.is_available:
        return
    author = ctx.message.author
    # Next, check that the author is either the same as the person who made the scene, or is a staff
    if info.created_by == author.id or is_staff(author):
        q.free_channel(db, ctx.message.channel.id)
        await ctx.send(embed=discord.Embed(description="End scene."))
        # Finally, reset the channel message.
        await ctx.message.channel.edit(
            reason=f"Scene ended by {author.display_name}",
            topic=
            "A roleplay channel. Type /scene your_scene_name in any channel to get started!"
        )
示例#10
0
 def __init__(self):
     # Make PostgreSQL Connection
     engine = get_database()
     try:
         self.con = engine.raw_connection()
         self.c = self.con.cursor()
         self.c.execute("""
             CREATE TABLE IF NOT EXISTS comments(
                 parent_id TEXT,
                 comment_id TEXT,
                 comment varchar(256),
                 subreddit TEXT,
                 subreddit_id TEXT,
                 created_utc INT,
                 controversiality INT,
                 score INT,
                 id SERIAL,
                 
                 PRIMARY KEY(parent_id, comment_id, subreddit_id, score)
             );
             """)
         self.con.commit()
     except Exception as ex:
         raise Exception('Error setting up postgres.', ex)
示例#11
0
 def setUp(self):
     tmpfile = tempfile.mktemp()
     self.db = db.get_database(file=tmpfile)
示例#12
0
def test_instantiate_db_runner():
    algorithm = PassthroughAlgorithm()
    db.get_database()  # Runner takes a db name, not an instance
    apr = AllPerceptRunner(algorithm, kConfig, constants.kTestFile)
示例#13
0
async def start_scene(ctx, *args):
    def reply(m):
        return m.channel == channel and m.author == author

        # Get user input stuff

    title = " ".join(args)
    if len(title) >= 256:
        await ctx.send(
            "I would love to open a scene for you, but your title is too long. Please try again, making sure to keep your title under 256 characters!"
        )
        return
    if len(title) == 0:
        await ctx.send(
            "It seems you didn't specify a scene title. Please try again!")
        return
    channel = ctx.message.channel
    author = ctx.message.author
    guild = ctx.message.channel.guild
    await ctx.send(
        f"I will start a scene named `{title}` for you. Which characters are in this scene?"
    )

    async with ctx.typing():
        msg = await ctx.bot.wait_for('message', check=reply)
        if await do_stop(ctx, msg):
            return
    characters = msg.content
    await ctx.send(
        "Okay! Where is the scene happening? Feel free to look at <#732651975061274734> for inspiration!"
    )

    async with ctx.typing():
        msg = await ctx.bot.wait_for('message', check=reply)
        if await do_stop(ctx, msg):
            return
    location = msg.content
    # Check the database to see if there is a free channel
    db = get_database("scene", guild.id)
    c = q.get_open_channel(db)
    if c is None:
        # Need to make the channel
        category = guild.get_channel(ROLEPLAY_CHANNELS_CATEGORY)
        channel_number = q.count_channels(db)
        channel = await guild.create_text_channel(f'rp-{channel_number + 1}',
                                                  category=category)
        # Update db to keep everything in sync
        q.add_new_channel(db, channel.id, channel.name)
        c = channel.id
    # Lock the channel
    q.reserve_channel(db, c, title, author.id)
    await ctx.send(f"Your scene has been opened in <#{c}>. Have fun!")

    # Notify channel of scene start
    channel = guild.get_channel(c)
    # Channel editing has low rate limit, so do it async
    asyncio.create_task(
        channel.edit(
            reason=f"Scene '{title}' started with {author.display_name}",
            topic=f"{title}: {characters} @ {location}"))

    scene_start = await channel.send(f"{author.mention} Scene started!",
                                     embed=get_scene_start_header(
                                         title, author,
                                         f"{characters} @ {location}"))
    # Put it in scene logs
    scenelog = guild.get_channel(SCENE_LOG)
    await scenelog.send(embed=get_scene_start_header(
        title, author, f"{characters} @ {location}",
        get_message_link(scene_start)))
示例#14
0
文件: service.py 项目: rutaq/asm3
def handler(post, path, remoteip, referer, querystring):
    """ Handles the various service method types.
    post:        The GET/POST parameters
    path:        The current system path/code.PATH
    remoteip:    The IP of the caller
    referer:     The referer HTTP header
    querystring: The complete querystring
    return value is a tuple containing MIME type, max-age, content
    """
    # Get service parameters
    account = post["account"]
    username = post["username"]
    password = post["password"]
    method = post["method"]
    animalid = post.integer("animalid")
    formid = post.integer("formid")
    seq = post.integer("seq")
    title = post["title"]
    strip_personal = post.integer("sensitive") == 0

    cache_key = querystring.replace(" ", "")

    # Do we have a cached response for these parameters?
    cached_response = get_cached_response(cache_key)
    if cached_response is not None:
        al.debug("cache hit for %s" % (cache_key), "service.handler")
        return cached_response

    # Are we dealing with multiple databases, but no account was specified?
    if account == "" and MULTIPLE_DATABASES:
        return ("text/plain", 0, 0, "ERROR: No database/alias specified")

    dbo = db.get_database(account)

    if dbo.database in ("FAIL", "DISABLED", "WRONGSERVER"):
        al.error(
            "auth failed - invalid smaccount %s from %s (%s)" %
            (account, remoteip, dbo.database), "service.handler", dbo)
        return ("text/plain", 0, 0,
                "ERROR: Invalid database (%s)" % dbo.database)

    # If the database has disabled the service API, stop now
    if not configuration.service_enabled(dbo):
        al.error("Service API is disabled (%s)" % method, "service.handler",
                 dbo)
        return ("text/plain", 0, 0, "ERROR: Service API is disabled")

    # Do any database updates need doing in this db?
    dbo.installpath = path
    if dbupdate.check_for_updates(dbo):
        dbupdate.perform_updates(dbo)

    # Does the method require us to authenticate? If so, do it.
    user = None
    securitymap = ""
    if method in AUTH_METHODS:
        # If the database has authenticated service methods disabled, stop now
        if not configuration.service_auth_enabled(dbo):
            al.error("Service API for auth methods is disabled (%s)" % method,
                     "service.handler", dbo)
            return ("text/plain", 0, 0,
                    "ERROR: Service API for authenticated methods is disabled")
        user = users.authenticate(dbo, username, password)
        if user is None:
            al.error(
                "auth failed - %s/%s is not a valid username/password from %s"
                % (username, password, remoteip), "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid username and password")
        securitymap = users.get_security_map(dbo, user["USERNAME"])

    # Get the preferred locale and timezone for the site
    l = configuration.locale(dbo)
    dbo.locale = l
    dbo.timezone = configuration.timezone(dbo)
    al.info("call %s->%s [%s %s]" % (username, method, str(animalid), title),
            "service.handler", dbo)

    if method == "animal_image":
        hotlink_protect("animal_image", referer)
        if utils.cint(animalid) == 0:
            al.error(
                "animal_image failed, %s is not an animalid" % str(animalid),
                "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            mediadate, data = media.get_image_file_data(
                dbo, "animal", utils.cint(animalid), seq)
            if data == "NOPIC":
                mediadate, data = media.get_image_file_data(dbo, "nopic", 0)
            return set_cached_response(cache_key, "image/jpeg", 86400, 3600,
                                       data)

    elif method == "animal_thumbnail":
        if utils.cint(animalid) == 0:
            al.error(
                "animal_thumbnail failed, %s is not an animalid" %
                str(animalid), "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            mediadate, data = media.get_image_file_data(
                dbo, "animalthumb", utils.cint(animalid), seq)
            if data == "NOPIC":
                mediadate, data = media.get_image_file_data(dbo, "nopic", 0)
            return set_cached_response(cache_key, "image/jpeg", 86400, 86400,
                                       data)

    elif method == "animal_view":
        if utils.cint(animalid) == 0:
            al.error(
                "animal_view failed, %s is not an animalid" % str(animalid),
                "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            return set_cached_response(
                cache_key, "text/html", 86400, 120,
                publishers.html.get_animal_view(dbo, utils.cint(animalid)))

    elif method == "animal_view_adoptable_js":
        return set_cached_response(
            cache_key, "application/javascript", 10800, 600,
            publishers.html.get_animal_view_adoptable_js(dbo))

    elif method == "animal_view_adoptable_html":
        return set_cached_response(
            cache_key, "text/html", 86400, 120,
            publishers.html.get_animal_view_adoptable_html(dbo))

    elif method == "dbfs_image":
        hotlink_protect("dbfs_image", referer)
        return set_cached_response(
            cache_key, "image/jpeg", 86400, 86400,
            utils.iif(title.startswith("/"),
                      dbfs.get_string_filepath(dbo, title),
                      dbfs.get_string(dbo, title)))

    elif method == "extra_image":
        hotlink_protect("extra_image", referer)
        return set_cached_response(cache_key, "image/jpeg", 86400, 86400,
                                   dbfs.get_string(dbo, title, "/reports"))

    elif method == "json_adoptable_animal":
        if utils.cint(animalid) == 0:
            al.error(
                "json_adoptable_animal failed, %s is not an animalid" %
                str(animalid), "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                       users.VIEW_ANIMAL)
            rs = publishers.base.get_animal_data(
                dbo,
                None,
                utils.cint(animalid),
                include_additional_fields=True)
            return set_cached_response(cache_key, "application/json", 3600,
                                       3600, utils.json(rs))

    elif method == "html_adoptable_animals":
        return set_cached_response(cache_key, "text/html", 10800, 1800, \
            publishers.html.get_adoptable_animals(dbo, style=post["template"], \
                speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid"), locationid=post.integer("locationid")))

    elif method == "html_adopted_animals":
        return set_cached_response(cache_key, "text/html", 10800, 1800, \
            publishers.html.get_adopted_animals(dbo, daysadopted=post.integer("days"), style=post["template"], \
                speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid")))

    elif method == "html_deceased_animals":
        return set_cached_response(cache_key, "text/html", 10800, 1800, \
            publishers.html.get_deceased_animals(dbo, daysdeceased=post.integer("days"), style=post["template"], \
                speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid")))

    elif method == "html_held_animals":
        return set_cached_response(cache_key, "text/html", 10800, 1800, \
            publishers.html.get_held_animals(dbo, style=post["template"], \
                speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid")))

    elif method == "json_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = publishers.base.get_animal_data(dbo,
                                             None,
                                             include_additional_fields=True)
        if strip_personal: rs = strip_personal_data(rs)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(rs))

    elif method == "jsonp_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = publishers.base.get_animal_data(dbo,
                                             None,
                                             include_additional_fields=True)
        if strip_personal: rs = strip_personal_data(rs)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(rs)))

    elif method == "xml_adoptable_animal":
        if utils.cint(animalid) == 0:
            al.error(
                "xml_adoptable_animal failed, %s is not an animalid" %
                str(animalid), "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                       users.VIEW_ANIMAL)
            rs = publishers.base.get_animal_data(
                dbo,
                None,
                utils.cint(animalid),
                include_additional_fields=True)
            return set_cached_response(cache_key, "application/xml", 3600,
                                       3600, html.xml(rs))

    elif method == "xml_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = publishers.base.get_animal_data(dbo,
                                             None,
                                             include_additional_fields=True)
        if strip_personal: rs = strip_personal_data(rs)
        return set_cached_response(cache_key, "application/xml", 3600, 3600,
                                   html.xml(rs))

    elif method == "json_found_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_FOUND_ANIMAL)
        rs = lostfound.get_foundanimal_last_days(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(rs))

    elif method == "jsonp_found_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_FOUND_ANIMAL)
        rs = lostfound.get_foundanimal_last_days(dbo)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(rs)))

    elif method == "xml_found_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_FOUND_ANIMAL)
        rs = lostfound.get_foundanimal_last_days(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   html.xml(rs))

    elif method == "json_lost_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_LOST_ANIMAL)
        rs = lostfound.get_lostanimal_last_days(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(rs))

    elif method == "jsonp_lost_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_LOST_ANIMAL)
        rs = lostfound.get_lostanimal_last_days(dbo)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(rs)))

    elif method == "xml_lost_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_LOST_ANIMAL)
        rs = lostfound.get_lostanimal_last_days(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   html.xml(rs))

    elif method == "json_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(rs))

    elif method == "jsonp_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(rs)))

    elif method == "xml_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/xml", 3600, 3600,
                                   html.xml(rs))

    elif method == "html_report":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_REPORT)
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, post)
        rhtml = reports.execute(dbo, crid, username, p)
        return set_cached_response(cache_key, "text/html", 600, 600, rhtml)

    elif method == "csv_mail" or method == "csv_report":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_REPORT)
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, post)
        rows, cols = reports.execute_query(dbo, crid, username, p)
        mcsv = utils.csv(l, rows, cols, True)
        return set_cached_response(cache_key, "text/csv", 600, 600, mcsv)

    elif method == "jsonp_recent_changes":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_recent_changes(dbo)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(sa)))

    elif method == "json_recent_changes":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_recent_changes(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(sa))

    elif method == "xml_recent_changes":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_recent_changes(dbo)
        return set_cached_response(cache_key, "application/xml", 3600, 3600,
                                   html.xml(sa))

    elif method == "jsonp_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_shelter_animals(dbo)
        if strip_personal: sa = strip_personal_data(sa)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(sa)))

    elif method == "json_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_shelter_animals(dbo)
        if strip_personal: sa = strip_personal_data(sa)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(sa))

    elif method == "xml_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_shelter_animals(dbo)
        if strip_personal: sa = strip_personal_data(sa)
        return set_cached_response(cache_key, "application/xml", 3600, 3600,
                                   html.xml(sa))

    elif method == "rss_timeline":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        return set_cached_response(cache_key, "application/rss+xml", 3600,
                                   3600, html.timeline_rss(dbo))

    elif method == "upload_animal_image":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.ADD_MEDIA)
        media.attach_file_from_form(dbo, username, media.ANIMAL, int(animalid),
                                    post)
        return ("text/plain", 0, 0, "OK")

    elif method == "online_form_html":
        if formid == 0:
            raise utils.ASMError(
                "method online_form_html requires a valid formid")
        return set_cached_response(cache_key, "text/html; charset=utf-8", 120,
                                   120,
                                   onlineform.get_onlineform_html(dbo, formid))

    elif method == "online_form_json":
        if formid == 0:
            raise utils.ASMError(
                "method online_form_json requires a valid formid")
        return set_cached_response(cache_key,
                                   "application/json; charset=utf-8", 30, 30,
                                   onlineform.get_onlineform_json(dbo, formid))

    elif method == "online_form_post":
        flood_protect("online_form_post", remoteip, 15)
        onlineform.insert_onlineformincoming_from_form(dbo, post, remoteip)
        redirect = post["redirect"]
        if redirect == "":
            redirect = BASE_URL + "/static/pages/form_submitted.html"
        return ("redirect", 0, 0, redirect)

    elif method == "sign_document":
        if formid == 0:
            raise utils.ASMError(
                "method sign_document requires a valid formid")
        if post["sig"] == "":
            return set_cached_response(cache_key, "text/html", 2, 2,
                                       sign_document_page(dbo, formid))
        else:
            media.sign_document(dbo, "service", formid, post["sig"],
                                post["signdate"])
            media.create_log(dbo, "service", formid, "ES02",
                             _("Document signed", l))
            return ("text/plain", 0, 0, "OK")

    else:
        al.error("invalid method '%s'" % method, "service.handler", dbo)
        raise utils.ASMError("Invalid method '%s'" % method)
示例#15
0
def typesdb():
	return db.get_database()
示例#16
0
def test_instantiate_db_runner():
	algorithm = PassthroughAlgorithm()
	db.get_database() # Runner takes a db name, not an instance
	apr = AllPerceptRunner(algorithm, kConfig, constants.kTestFile)
示例#17
0
文件: cron.py 项目: rutaq/asm3
def run_default_database(mode):
    dbo = db.get_database()
    dbo.timeout = 0
    dbo.connection = dbo.connect()
    run(dbo, mode)
示例#18
0
文件: cron.py 项目: rutaq/asm3
def run_all_map_databases(mode):
    for alias in MULTIPLE_DATABASES_MAP.iterkeys():
        dbo = db.get_database(alias)
        dbo.timeout = 0
        dbo.connection = dbo.connect()
        run(dbo, mode)
示例#19
0
文件: models.py 项目: looneym/sobotka
 class Meta:
     database = sobotka_db.get_database()
示例#20
0
文件: test_db.py 项目: Bercio/gourmet
 def setUp(self):
     tmpfile = tempfile.mktemp()
     self.db = db.get_database(file=tmpfile)
示例#21
0
def testdb():
	return db.get_database()
示例#22
0
    :PROJECT_PATH: is absolute path for project directory.
    :DATABASES: is dictionary containg :sqlalchemy: declarative bases.
    :HOST: is dictionary containg :address: and :host: for run :Sainc: server.
'''
from os.path import dirname, abspath
from db import get_database

from secret import DATABASE_NAME, DATABASE_HOST, DATABASE_PORT, DATABASE_USER, DATABASE_PASSWORD

PROJECT_PATH = dirname(abspath(__file__))

MAIN_DATABASE_PATH = 'write-off.db'

DATABASES = {
    'main':
    get_database(echo=True, drivername='sqlite', database=MAIN_DATABASE_PATH),
    'outside':
    get_database(echo=True,
                 drivername='mysql+pymysql',
                 host=DATABASE_HOST,
                 port=DATABASE_PORT,
                 database=DATABASE_NAME,
                 username=DATABASE_USER,
                 password=DATABASE_PASSWORD,
                 query={'charset': 'cp1251'})
}

UPLOAD_ATTEMPTS_COUNT = 5

HOST = {'address': '0.0.0.0', 'port': 8000}
示例#23
0
def exportdb():
    return db.get_database()
示例#24
0
async def on_raw_message_delete(payload):
    db = get_database("leaderboard", payload.guild_id)
    q.delete_message(db, payload.message_id)
    print(f'Deleted msg with id {payload.message_id}')
示例#25
0
文件: users.py 项目: tgage/asm3
def web_login(post, session, remoteip, path):
    """
    Performs a login and sets up the user's session.
    Returns the username on successful login, or:
        FAIL        - problem with user/pass/account/ip
        DISABLED    - The database is disabled
        WRONGSERVER - The database is not on this server
    """
    database = post["database"]
    username = post["username"]
    password = post["password"]
    mobileapp = post["mobile"] == "true"
    nologconnection = post["nologconnection"] == "true"
    if len(username) > 100:
        username = username[0:100]

    dbo = db.get_database(database)

    if dbo.database in ("FAIL", "DISABLED", "WRONGSERVER"):
        return dbo.database

    # Connect to the database and authenticate the username and password
    user = authenticate(dbo, username, password)
    if user is not None and not authenticate_ip(user, remoteip):
        al.error(
            "user %s with ip %s failed ip restriction check '%s'" %
            (username, remoteip, user.IPRESTRICTION), "users.web_login", dbo)
        return "FAIL"

    if user is not None and "DISABLELOGIN" in user and user.DISABLELOGIN == 1:
        al.error(
            "user %s with ip %s failed as account has logins disabled" %
            (username, remoteip), "users.web_login", dbo)
        return "FAIL"

    if user is not None:
        al.info("%s successfully authenticated from %s" % (username, remoteip),
                "users.web_login", dbo)

        try:
            dbo.locked = configuration.smdb_locked(dbo)
            dbo.timezone = configuration.timezone(dbo)
            dbo.installpath = path
            session.locale = configuration.locale(dbo)
            dbo.locale = session.locale
            session.dbo = dbo
            session.user = user.USERNAME
            session.superuser = user.SUPERUSER
            session.mobileapp = mobileapp
            update_session(session)
        except:
            al.error("failed setting up session: %s" % str(sys.exc_info()[0]),
                     "users.web_login", dbo, sys.exc_info())
            return "FAIL"

        try:
            session.securitymap = get_security_map(dbo, user.USERNAME)
        except:
            # This is a pre-3002 login where the securitymap is with
            # the user (the error occurs because there's no role table)
            al.debug("role table does not exist, using securitymap from user",
                     "users.web_login", dbo)
            session.securitymap = user.SECURITYMAP

        try:
            ur = get_users(dbo, user.USERNAME)[0]
            session.roles = ur.ROLES
            session.roleids = ur.ROLEIDS
            session.siteid = utils.cint(user.SITEID)
            session.locationfilter = utils.nulltostr(user.LOCATIONFILTER)
        except:
            # Users coming from v2 won't have the
            # IPRestriction or EmailAddress fields necessary for get_users - we can't
            # help them right now so just give them an empty set of
            # roles and locationfilter until they login again after the db update
            session.roles = ""
            session.roleids = ""
            session.locationfilter = ""
            session.siteid = 0

        try:
            # Mark the user logged in
            if not nologconnection:
                audit.login(dbo, username, remoteip)

            # Check to see if any updates need performing on this database
            if dbupdate.check_for_updates(dbo):
                dbupdate.perform_updates(dbo)
                # We did some updates, better reload just in case config/reports/etc changed
                update_session(session)

            # Check to see if our views and sequences are out of date and need reloading
            if dbupdate.check_for_view_seq_changes(dbo):
                dbupdate.install_db_views(dbo)
                dbupdate.install_db_sequences(dbo)

        except:
            al.error("failed updating database: %s" % str(sys.exc_info()[0]),
                     "users.web_login", dbo, sys.exc_info())

        try:
            al.info("%s logged in" % user.USERNAME, "users.login", dbo)
            update_user_activity(dbo, user.USERNAME)
        except:
            al.error(
                "failed updating user activity: %s" % str(sys.exc_info()[0]),
                "users.web_login", dbo, sys.exc_info())
            return "FAIL"
    else:
        al.error(
            "database:%s username:%s password:%s failed authentication from %s"
            % (database, username, password, remoteip), "users.web_login", dbo)
        return "FAIL"

    return user.USERNAME
示例#26
0
def check_for_table():
	sql = 'SELECT COUNT(*) AS exist FROM information_schema.tables WHERE table_schema="' + db.get_database() + '" AND table_name="' + db.validate(data[0]) + '";'
	cur = db.execute_sql(sql)
	tmp = cur.fetchone()['exist']
	if tmp > 0:
		print 'table \'' + data[0] + '\' already exists'
		return True;
	return False
示例#27
0
def exportdb():
	return db.get_database()