Exemple #1
0
from sqlalchemy.orm import session
from connection import Connection
from models import Product

session = Connection().create_session()

m = Product(name='Cookie', price=3, count=2)

session.add(m)
session.commit()
Exemple #2
0
 def test_create(self):
     con = Connection("http://127.0.0.1:9888")
     key = Keys.create(con, "sheng", "123456")
     print(key.alias, key.xpub, key.file)
     self.assertIsNotNone(key)
Exemple #3
0
 def test_delete_by_alias(self):
     con = Connection("http://127.0.0.1:9888")
     status = Keys.delete_by_alias(con, "sheng", "123456")
     self.assertIs("true", status)
Exemple #4
0
 def __init__(self):
     Connection.__init__(self)
     self.loginfo = Connection()
     self.masterhandle = ''
     self.home = ''
Exemple #5
0
 def create(address=None, port=None):
     return Minecraft(Connection(address, port))
Exemple #6
0
""" compute the average, std, median and percentile of the bookings/parkings duration for the 2017/10"""

from time import time
import numpy as np
import pandas as pd
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
from connection import Connection
from pipeline_ict4ts import pip_d

client = Connection()
db = client.db

start = datetime.timestamp(datetime(2017, 10, 1))
end = datetime.timestamp(datetime(2017, 10, 31, 23, 59))

start_ = time()
to_b_d_month = list(db['PermanentBookings'].aggregate(
    pip_d(start_timestamp=start, end_timestamp=end)))
to_p_d_month = list(db['PermanentParkings'].aggregate(
    pip_d(start_timestamp=start, end_timestamp=end)))

po_p_d_month = list(db['PermanentParkings'].aggregate(
    pip_d(start_timestamp=start, end_timestamp=end, city='Portland')))
po_b_d_month = list(db['PermanentBookings'].aggregate(
    pip_d(start_timestamp=start, end_timestamp=end, city='Portland')))

eto_b_d_month = list(db['enjoy_PermanentBookings'].aggregate(
Exemple #7
0
    def Press(self, event):
        #每次按下鼠标都会i+1,因此按下鼠标画下的图形都会有为一个标记
        if self.state == "oval":
            self.CircleNum += 1
        self.i += 1
        self.x = event.x
        self.y = event.y
        if self.state == 'oval':
            num = self.canvas.create_oval(self.x - 30,
                                          self.y - 30,
                                          self.x + 30,
                                          self.y + 30,
                                          outline=self.color,
                                          tags='line' + str(self.CircleNum),
                                          width=2)
            # print(num)
            self.Circle.append(Circle(self.x, self.y, num, self.CircleNum))
            self.canvas.create_text(self.x, self.y, text=self.CircleNum)
            node = Node(self.CircleNum)
            self.NodeCollection.add_node(node)
        if self.state == 'StartCircle':
            for c in self.Circle:
                if math.sqrt(
                        math.fabs(event.x - c.x) * math.fabs(event.x - c.x) +
                        math.fabs(event.y - c.y) *
                        math.fabs(event.y - c.y)) < (30):
                    self.canvas.itemconfig(c.num, outline="red")
                    c.start = 1
        if self.state == 'EndCircle':
            for c in self.Circle:
                if math.sqrt(
                        math.fabs(event.x - c.x) * math.fabs(event.x - c.x) +
                        math.fabs(event.y - c.y) *
                        math.fabs(event.y - c.y)) < (30):
                    self.canvas.itemconfig(c.num, outline="blue")
                    c.start = 0
        if self.state == 'line':
            self.DoubleNodeList.clear()
            # 如果找不到tag为line的组件,则生成tag为line的组件
            startCircle = []
            endCircle = []
            for c1 in self.Circle:
                if c1.start == 1:
                    startCircle.append(c1)
                elif c1.start == 0:
                    endCircle.append(c1)
            for c3 in startCircle:
                for c4 in endCircle:
                    a = c3.x - c4.x
                    b = c3.y - c4.y
                    if a < 0 and b < 0:
                        self.canvas.create_line(c3.x + 20,
                                                c3.y + 20,
                                                c4.x - 20,
                                                c4.y - 20,
                                                fill=self.color,
                                                tags='line',
                                                width=2,
                                                arrow="last",
                                                arrowshape='8 10 3')
                    elif a < 0 and b > 0:
                        self.canvas.create_line(c3.x + 20,
                                                c3.y - 20,
                                                c4.x - 20,
                                                c4.y + 20,
                                                fill=self.color,
                                                tags='line',
                                                width=2,
                                                arrow="last",
                                                arrowshape='8 10 3')

                    elif a > 0 and b > 0:
                        self.canvas.create_line(c3.x - 20,
                                                c3.y - 20,
                                                c4.x + 20,
                                                c4.y + 20,
                                                fill=self.color,
                                                tags='line',
                                                width=2,
                                                arrow="last",
                                                arrowshape='8 10 3')
                    elif a > 0 and b < 0:
                        self.canvas.create_line(c3.x - 20,
                                                c3.y + 20,
                                                c4.x + 20,
                                                c4.y - 20,
                                                fill=self.color,
                                                tags='line',
                                                width=2,
                                                arrow="last",
                                                arrowshape='8 10 3')
            #开始节点列表
            startNodeList = []
            #结束节点列表
            endNodeList = []
            #获取
            for start in startCircle:
                startNode = self.NodeCollection.get_Node(start.CircleNum)
                startNodeList.append(startNode)
            for end in endCircle:
                endNode = self.NodeCollection.get_Node(end.CircleNum)
                endNodeList.append(endNode)

            for start in startCircle:
                start_node = self.NodeCollection.get_Node(start.CircleNum)
                start_node.add_UpNodeS(endNodeList)

            for end in endCircle:
                end_node = self.NodeCollection.get_Node(end.CircleNum)
                end_node.add_DownNodeS(startNodeList)

            # for node in self.NodeCollection.node_list():
            #     print("节点序号:",node.node_index)
            #
            #     print("下游节点:")
            #     for downstream in node.get_downstream():
            #         print(downstream.node_index)
            #
            #     print("上游节点:")
            #     for upstream in node.get_upstream():
            #         print(upstream.node_index)

            for c in self.Circle:
                c.start = -1
                self.canvas.itemconfig(c.num, outline="black")

            E = self.get_E_V()
            # for f in V:
            #     print(f.node_index)
            self.DoubleNodeList.extend(E)
            self.ConnectionS.clear()

            print(self.DoubleNodeList.__len__())
            for node1, node2 in self.DoubleNodeList:
                ##创建线并添加进集合
                con = Connection(node2, node1)
                self.ConnectionS.append(con)
                print("(", node1.node_index, node2.node_index, ")")

            for conn in self.ConnectionS:
                conn.downstream_node.append_upstream(conn)
                conn.upstream_node.append_downstream(conn)

            print(self.ConnectionS.__len__())
Exemple #8
0
    def run(self):
        """Called when the slot-thread is started.

        The slot will wait for a chunk-job on a Download's chunk_queue.
        Then it requests the Source to use from the Download.
        Maybe it will wait some seconds before start loading the data
        using a Connection-object.
        Using EventListeners the download will be informed about events.
        """
        while self._download.is_loading():
            self.data_received = False

            while self._chunk is None:
                try:
                    self._chunk = self._download.chunk_queue.get(True, 0.2)
                except Empty, e:
                    self._chunk = None

                # Download may be paused --> stop downloading
                if not self._download.is_loading():
                    return

            if self._chunk.length is None:
                self._log.add_log_entry(
                    MessageType.info, self.getName(),
                    'Got new chunk-job (offset={0})!'.format(
                        self._chunk.offset + self._chunk.loaded))
            else:
                self._log.add_log_entry(
                    MessageType.info, self.getName(),
                    'Got new chunk-job (offset={0}, length={1})!'.format(
                        self._chunk.offset + self._chunk.loaded,
                        self._chunk.length - self._chunk.loaded))

            source, wait_until = None, 0
            if self.connection is None:
                # request source
                source, wait_until = self._download.get_next_source()

                self._download.source_condition.acquire()
                while source is None and self._download.is_loading():
                    self._log.add_log_entry(MessageType.info, self.getName(),
                                            'Waiting for a source!')
                    self._download.source_condition.wait()
                    if self._download.is_loading():
                        source, wait_until = self._download.get_next_source()

                self._download.source_condition.release()

            else:
                # use source of current connection (from InfoSlot)
                source, wait_until = (
                    self.connection.source,
                    self.connection.source.is_retry_allowed())

            # source may be None, e.g. when max retries is reached
            # on each source, or source does not support more slots
            if source is None:
                self.chunk_failed_event.signal(
                    self._chunk,
                    source,
                    ioerror=False,
                    data_received=self.data_received)
                return

            self._log.add_log_entry(MessageType.info, self.getName(),
                                    'Using the source {0}'.format(source.url))

            # maybe we need to wait some seconds between retries
            to_wait = wait_until - time()
            if to_wait > 0:
                self._log.add_log_entry(
                    MessageType.info, self.getName(),
                    'Retry in {0} seconds!'.format(to_wait))
                # wait until retry, but still check if state has changed
                while time() < wait_until:
                    sleep(0.2)
                    if not self._download.is_loading():
                        return

            # Download may be paused --> stop downloading
            #if not self._download.is_loading():
            #    print(self.getName() + ': DL is not loading anymore (state changed)')
            #    return

            # is chunk still valid? (after waiting retry-time)
            self._download.fix_chunk(self._chunk)
            if self._chunk.length == 0:
                self.chunk_finished_event.signal(
                    source, data_received=self.data_received)
                return

            # use already opened connection (from InfoSlot)
            c = self.connection
            if c is None:
                c = Connection(source)

            def received_listener():
                source.inc_active_slots()
                self.data_received = True
                self.chunk_started_event.signal(self._chunk)

            def on_fetch_stopped():
                if self.data_received:
                    source.inc_active_slots(decrement=True)

            c.data_received_event.add_listener(received_listener)
            try:
                c.fetch_data(self._chunk, self._target_file, self._download)
            except HTTPError, e:
                on_fetch_stopped()
                source.add_fail(self.data_received)
                self._log.add_log_entry(MessageType.error, self.getName(),
                                        'HTTP-Error: ' + str(e))
                self.chunk_failed_event.signal(
                    self._chunk,
                    source,
                    ioerror=False,
                    data_received=self.data_received)
Exemple #9
0
 def make_connection(self):
     kwargs = self._kwargs
     kwargs['pool'] = self
     return Connection(*self._args, **kwargs)
@contextlib.contextmanager
def start_transaction(connection):
    tx = Transaction(connection)

    try:
        yield tx
    except:
        tx.rollback()
        raise

    tx.commit()


if __name__ == "__main__":
    conn = Connection()
    try:
        with start_transaction(conn) as tx:
            x = 1 + 1
            raise ValueError()  # trigger error
            y = x + 2
            print('transaction 0 =', x, y)
    except ValueError:
        print('Oops! Transaction 0 failed.')

    print('\n')

    try:
        with start_transaction(conn) as tx:
            x = 1 + 1
            y = x + 2
Exemple #11
0
    def __init__(self, port):
        self.connection = Connection(port)

        self.width, self.height = 200, 200
        self.window = pyglet.window.Window(self.width, self.height)
        self.last = 0
Exemple #12
0
 def run(self, conn):
     try:
         conn = Connection(conn)
         session = Session(conn, Mailbox=self.Mailbox)
     finally:
         conn.close()
    def handle(self, sock):

        try:
            connection = Connection(sock, self.savedata, "", self.savedataFolder, "dataset")

            # First message is the config (file or text)
            config = next(connection)

            # Break out if a connection was established but no data was received
            if ((config is None) & (connection.is_exhausted is True)):
                logging.info("Connection closed without any data received")
                return

            # Second messages is the metadata (text)
            metadata_xml = next(connection)
            logging.debug("XML Metadata: %s", metadata_xml)
            try:
                metadata = ismrmrd.xsd.CreateFromDocument(metadata_xml)
                if (metadata.acquisitionSystemInformation.systemFieldStrength_T != None):
                    logging.info("Data is from a %s %s at %1.1fT", metadata.acquisitionSystemInformation.systemVendor, metadata.acquisitionSystemInformation.systemModel, metadata.acquisitionSystemInformation.systemFieldStrength_T)
            except:
                logging.warning("Metadata is not a valid MRD XML structure.  Passing on metadata as text")
                metadata = metadata_xml

            # Decide what program to use based on config
            # As a shortcut, we accept the file name as text too.
            if (config == "simplefft"):
                logging.info("Starting simplefft processing based on config")
                simplefft.process(connection, config, metadata)
            elif (config == "invertcontrast"):
                logging.info("Starting invertcontrast processing based on config")
                invertcontrast.process(connection, config, metadata)
            elif (config == "analyzeflow"):
                logging.info("Starting analyzeflow processing based on config")
                analyzeflow.process(connection, config, metadata)
            elif (config == "null"):
                logging.info("No processing based on config")
                try:
                    for msg in connection:
                        if msg is None:
                            break
                finally:
                    connection.send_close()
            elif (config == "savedataonly"):
                # Dummy loop with no processing
                try:
                    for msg in connection:
                        if msg is None:
                            break
                finally:
                    connection.send_close()
            else:
                logging.info("Unknown config '%s'.  Falling back to 'invertcontrast'", config)
                invertcontrast.process(connection, config, metadata)

        except Exception as e:
            logging.exception(e)

        finally:
            # Encapsulate shutdown in a try block because the socket may have
            # already been closed on the other side
            try:
                sock.shutdown(socket.SHUT_RDWR)
            except:
                pass
            sock.close()
            logging.info("Socket closed")

            # Dataset may not be closed properly if a close message is not received
            if connection.savedata is True:
                try:
                    connection.dset.close()
                except:
                    pass
                logging.info("Incoming data was saved at %s", connection.mrdFilePath)
Exemple #14
0
 def _init_connection(self, db):
     db = self._normalize_db(db)
     if db not in self._connections:
         # create new connection
         self._connections[db] = Connection(self._build_connection_hash(db))
Exemple #15
0
def validate_light_id(light_id):
    # TODO: not this
    connection = Connection().connect()
    if light_id not in [l.light_id for l in connection.lights]:
        raise InvalidLightIDError
Exemple #16
0
async def async_main():
    s = ''
    while s not in ('C', 'J', 'O'):
        print('(C)reate, (J)oin, c(O)nnect? ', end='')
        s = input().upper()

    async with aiohttp.ClientSession() as session:
        if s == 'C':
            async with session.get('http://localhost:8080/create',
                                   params={'name': 'player1'}) as response:
                j = await response.json()
                game_id = j['game_id']
                player_id = j['player_id']
        elif s == 'J':
            print('Enter game_id: ', end='')
            game_id = int(input())
            async with session.get('http://localhost:8080/join',
                                   params={'name': 'player2'}) as response:
                j = await response.json()
                player_id = j['player_id']
        elif s == 'O':
            print('Enter game_id: ', end='')
            game_id = int(input())
            print('Enter player_id: ', end='')
            player_id = int(input())

        # create client
        connection = Connection()
        client = Client(game_id, player_id, connection)
        client_lock = Lock()

        render_thread = Thread(target=render, args=(client, client_lock))
        render_thread.start()

        # connect
        codec = Codec()
        for obj in (protocol.GetGameRequest, protocol.GetGameResponse,
                    protocol.MoveCharRequest, model.Game, model.Player,
                    model.Maze, model.Unit):
            codec.register(obj)

        logging.debug('Connecting...')
        async with session.ws_connect(
                f'http://localhost:8080/connect?game_id={game_id}&player_id={player_id}'
        ) as ws:
            logging.debug('Connected')
            logging.debug('DIR = %s', dir(ws))

            client.fetch_game()
            while connection.outgoing:
                message = connection.outgoing.pop(0)
                await ws.send_str(codec.encode(message))

            async for msg in ws:
                if msg.type == aiohttp.WSMsgType.TEXT:
                    message = codec.decode(msg.data)
                    connection.incoming.append(message)
                    with client_lock:
                        client.process_connection()
                    while connection.outgoing:
                        message = connection.outgoing.pop(0)
                        await ws.send_str(codec.encode(message))
                elif msg.type == aiohttp.WSMsgType.CLOSED:
                    logging.debug('Websocket closed')
                    break
                elif msg.type == aiohttp.WSMsgType.ERROR:
                    logging.debug('Websocket error')
                    break
Exemple #17
0
 def handle_connection(self, stream, address, callback):
     # todo: fix not doing fast resume on bitmask
     #logging.info('client Handle conn! %s' % self)
     connection = Connection(stream, address, callback, has_connected=True)
     connection.set_client(self)
Exemple #18
0
 def __init__(self, b2c2_base_url, api_token):
     self.b2c2_base_url = b2c2_base_url
     self.api_token = api_token
     self._connection = Connection(b2c2_base_url=b2c2_base_url,
                                   api_token=api_token)
     self.logger = logger
def status_download_file(excel_writer, intake_value, selected_cells, hist):
    selected_cells = literal_eval(selected_cells)
    fm_all, fm_filter = fase_check()
    xaris_df = []
    if intake_value == 'Xaris_vs_Connect':
        xaris_df = xaris()
        xaris_df = xaris_df.df.to_dict()

    if hist:
        fm = fm_filter
    else:
        fm = fm_all

    df_out, _, _ = get_status_df(intake_value, selected_cells, fm, xaris_df)

    # ophalen extra data voor gedetaileerde tabel;
    with Connection('r', 'download_status_check') as session:
        if 'ln_id' in df_out.columns:
            ln = read(session,
                      sourceTag=sourcetag1,
                      key=df_out[id].drop_duplicates().tolist(),
                      measure=measures1).reset_index()
            df_out = df_out.merge(ln, left_on=id,
                                  right_on='sourceKey').drop('sourceKey',
                                                             axis=1)

        if 'bpnr' in df_out.columns:
            cp_keys_q = sa.text('''
            SELECT kindKey, parentKindKey FROM czHierarchy
            WHERE parentKind = 'cpnr_extracted'
            AND kind = 'cp_id'
            AND versionEnd IS NULL
            AND parentKindKey IN :ids
            ''')
            cp_coupling = pd.read_sql(
                cp_keys_q,
                session.bind,
                params={
                    'ids':
                    df_out['bpnr'].fillna('').drop_duplicates().tolist()
                })
            cp = read(session,
                      sourceTag=sourcetag2,
                      key=cp_coupling['kindKey'].tolist(),
                      measure=measures2)
            cp_coupling = cp_coupling.rename(columns={
                'kindKey': 'sourceKey',
                'parentKindKey': 'bpnr'
            })
            cp = cp.reset_index().merge(cp_coupling,
                                        on='sourceKey',
                                        how='left').drop('sourceKey', axis=1)
            df_out = df_out.merge(cp, on='bpnr')
            df_out = df_out[df_out4]

        if opdracht_id in df_out.columns:
            lijst = df_out[opdracht_id].fillna('').drop_duplicates().tolist()
            q = sa.select([czHierarchy.kindKey]).\
                where(czHierarchy.parentKindKey.in_(lijst)).\
                where(czHierarchy.parentKind == opdracht_id).\
                where(czHierarchy.kind == 'con_objectid').\
                where(czHierarchy.versionEnd.is_(None))
            keys = [r for r, in session.execute(q).fetchall()]
            connect = read(session,
                           sourceTag=sourcetag3,
                           key=keys,
                           measure=measures3)
            connect = connect.reset_index().rename(
                columns={'sourceKey': 'con_objectid'})
            df_out = df_out.merge(connect, on=opdracht_id)
            df_out = df_out[df_out5]

    df_out.to_excel(excel_writer, sheet_name='status', index=False)
    ws = excel_writer.sheets['status']
    ws.freeze_panes(1, 0)
    ws.set_column('A:AH', 22)
    ws.autofilter(0, 0, df_out.shape[0], df_out.shape[1] - 1)

    return excel_writer
Exemple #20
0
# import matplotlib as mpl
# mpl.use('Agg', warn=False)
import matplotlib.pyplot as plt
from connection import Connection
import strengthen_functions
import numpy as np

np.random.seed()
# ax1, ax2 = plt.subplots(1, 2)
# plt.figure(figsize=(10, 3))
# fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 3))
fig, ax = plt.subplots(1, 1, figsize=(10, 3))
for i in range(11):
    conn = Connection(init_strength=.1 * i,
                      pf=strengthen_functions.PF30,
                      transmission_history_len=10**4)
    strength = []
    frequency = []
    for i in range(20 * 10**4):
        conn.propagate_once(stimulus_prob=.8)
        strength.append(conn.get_strength())
        # frequency.append(conn.get_frequency())
    ax.plot(strength, alpha=.8)
    # ax2.plot(frequency, alpha=.2, color='black')
    # ax1.set_xlabel('(a)')
    # ax2.set_xlabel('(b)')
    ax.set_ylim(0, 1)
    # ax2.set_ylim(0, 1)
# plt.grid(True)
plt.savefig('conn_06.png')
plt.show()
Exemple #21
0
 def connection(self):
     if self._connection is None:
         self._connection = Connection()
     return self._connection
Exemple #22
0
 def get_conn(self):
     if self._conn is None:
         self._conn = Connection(self.host, self.port)
     return self._conn
Exemple #23
0
def get_conn(section='ldap',
             prefix='ldap.',
             filename=os.path.expanduser('~/.ldap.cfg')):
    return Connection(section=section, prefix=prefix, filename=filename)
Exemple #24
0
 def new_connection_handler(socket, address):
     logger.info("New incoming connection")
     connection = Connection(node, socket, address)
     connection.start()
Exemple #25
0
 def test_find_by_alias(self):
     con = Connection("http://127.0.0.1:9888")
     key = Keys.find_by_alias(con, "sender-key")
     print(key.alias, key.xpub, key.file)
     self.assertIsNotNone(key)
Exemple #26
0
 def __init__(self, config):
     self._config = config
     self._connection = Connection(config.serverUri)
Exemple #27
0
 def test_delete(self):
     con = Connection("http://127.0.0.1:9888")
     xpub = Keys.find_by_alias(con, "sheng").xpub
     status = Keys.delete(con, xpub, "123456")
     self.assertIs("true", status)
     pass
Exemple #28
0
def store():
    conn = Connection()
    store = Store(conn.get_connection())
    event_store = EventStore(store)
    return event_store
Exemple #29
0
 def test_reset_password(self):
     con = Connection("http://127.0.0.1:9888")
     xpub = Keys.find_by_alias(con, "sheng").xpub
     print(xpub)
     status = Keys.reset_password(con, xpub, "567890", "123456")
     self.assertIs("true", status)
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN,
        UserType.MENTOR,
        UserType.FREE,
        UserType.PAID
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    body = json.loads(event["body"])
    try:
        requestor = body['requestor']
        requestee = body['requestee'] 
    except:
        return http_status.bad_request("missing body attribute(s): 'requestor' or 'requestee'")

    try:
        requestor_email = requestor['email']
        requestor_type = requestor['user_type']
        requestor_name = requestor['name']
        requestee_email = requestee['email']
        requestee_type = requestee['user_type']
        requestee_name = requestee['name']
    except:
        return http_status.bad_request("missing body attribute(s): 'user_type', 'email' or 'name'")

    session = Session()
    connections = session.query(Connection).all()
    create_conn = True
    for connection in connections:
        if (connection.requestor == requestor_email and connection.requestee == requestee_email) \
            or (connection.requestor == requestee_email and connection.requestee == requestor_email):
            if connection.connection_status == ConnectionStatus.PENDING:
                if connection.requestor == requestee_email and connection.requestee == requestor_email:
                    connection.connection_status = ConnectionStatus.ACCEPTED

                    template_data = {
                        "requestee_name": str(requestee_name),
                        "requestor_name": str(requestor_name)
                    }
                    template_data = json.dumps(template_data)
                    recipients = [requestor_email,requestee_email]
                    send_templated_email(recipients, "Connection-Confirmation-SEtoSE", template_data)    

                    create_conn = False
                    break

                session.close()
                return http_status.bad_request("connections request already sent")
            elif connection.connection_status == ConnectionStatus.ACCEPTED:
                session.close()
                return http_status.bad_request("connections request already established")

    if create_conn:
        if requestee_type == "MENTOR" and requestor_type == "MENTOR":
            new_connection = Connection(requestor=requestor_email, requestee=requestee_email, connection_status=ConnectionStatus.PENDING)
            session.add(new_connection)

            template_data = {
                "requestee_name": str(requestee_name),
                "requestor_name": str(requestor_name)
            }
            template_data = json.dumps(template_data)
            recipients = [requestee_email]
            send_templated_email(recipients, "Connection-Initiation-SEtoSE", template_data)    



        elif requestee_type == "MENTEE" and requestor_type == "MENTOR":
            new_connection = Connection(requestor=requestor_email, requestee=requestee_email, connection_status=ConnectionStatus.ACCEPTED)
            session.add(new_connection)

            # The send_templated_email function requires JSON Formatted Data with " strings "
            template_data = {
                "requestee_name": str(requestee_name),
                "requestor_name": str(requestor_name)
            }
            template_data = json.dumps(template_data)
            recipients = [requestor_email, requestee_email]
            send_templated_email(recipients, "Connection-Initiation-SEtoAP", template_data)           

        else:
            return http_status.bad_request("A connection can only be initiated by a mentor")

    session.commit()
    session.close()

    return http_status.success()