Import a specific macro from a module in Nim - nim-lang

I import the json module just to use its useful %* macro:
import json # for %*
let json_payload = $(%* {"username": "admin", "password": "1234"})
Is it possible to import just this particular macro from the module? Something like this (though obviously this doesn't work):
from json import %*

you can absolutely do that, but for operators you need to surround them with backticks. you are also using $ from json so you need to import that too:
from json import `%*`,`$`
let json_payload = $(%* {"username": "admin", "password": "1234"})
echo json_payload #{"username":"admin","password":"1234"}

Related

fastapi how to read nested json as dictionary?

I am trying to receive the following JSON:
{
"va": "{1: 5, 2:1, 3:5}"
}
in my main.py I have the following:
from typing import Optional, Dict
from fastapi import FastAPI
from pydantic import BaseModel
class rq(BaseModel):
va: Dict[str, str]
app = FastAPI(debug=True)
#app.post("/hello")
async def create_item(rq: rq):
return 1
but I get
"msg": "value is not a valid dict",
"type": "type_error.dict"
how may I receive va as dict to iterate over it?
When you create a model, every field is actually a key-value pair, so with your example it expects something like this:
{
"va": {"some":"value"}
}
But what you send is
"va": str
So i don't know how you send the value but you are definitely sending a str instead of a Dict[str, str]

Custom Search Command Discord.py

I'm attempting to make a Custom Search command using the Custom Search API.
Naturally I have no idea how to implement it. I'm hoping someone can take a look at what I have and help me figure out how to make it work in this style?
import discord
from discord.ext import commands
import discord.utils
import time
import os
import dotenv
from dotenv import load_dotenv
load_dotenv()
SEARCH = os.getenv("CUSTOM_SEARCH_API_KEY")
class Util(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command(name="Search", aliases=["search"])
#commands.has_permissions(embed_links=True, add_reactions=True)
async def _search(self, ctx, *, message):
if not ctx.author.Bot:
guild = ctx.guild
msg = ctx.message
cli = self.client.user
gold = discord.Color.dark_gold()
embed = discord.Embed(color=gold, name=f"{image.name}", description=f"{image.desc}", timestamp=msg.created_at)
embed.set_image(url=f"{image.url}")
embed.set_thumbnail(url=cli.avatar_url)
embed.set_footer(text=guild.name, icon_url=guild.icon_url)
await ctx.send(embed=embed)
return
def setup(client):
client.add_cog(Util(client))
I'm using dotenv to store my API key
Basically, I'm wanting it to be a somewhat detailed command.
If searching for posts it will find the exact post. and if searching for images it will go by tag and find a random image matching the selected tag(s).
I would like for it to respond via rich embed if possible.
I'm fully aware my above code won't work at all. I simply put it there as a base for part of the embed that I want to try to implement.
Some help would be much appreciated.
I'm using discord.py rewrite and I have my commands set up through cogs.
This is my bot.py file that contains the handler for my cogs.
import discord
from discord.ext import commands
import os
import json
import dotenv
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
PREFIX = os.getenv("COMMAND_PREFIX")
client = commands.Bot(command_prefix=PREFIX)
client.remove_command('help')
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")
client.run(TOKEN)

Mocking global/module level variables in Python

I have a module that looks like this:
import psycopg2
client = vault_client(vault_url, vault_certs_path, credentials)
vault_data = client.read(vault_path)['data']
def do_thing
connection = psycopg2.connect(
dbname=vault_data['database'],
host=vault_data['cluster_name'],
...
)
How do I test this do_thing method. I need to mock out vault_data and the import of psycopy2. I need to ensure:
That the psycopg2.connect methods receives the right arguments
How do I mock the vault_client method to return a mock that then returns a dictionary when the read method is called on the mock?
I have this but the real methods get called:
#mock.patch("sources.segment.handler")
#mock.patch("sources.segment.handler.psycopg2")
def test_attempts_to_connect_to_redshift(self, mock_psycopg2, mock_handler):
mock_handler.vault_client.return_value = {
"data": {
"database": "some_database",
"cluster_name": "some_cluster_name",
"port": "some_port",
"username": "some_username",
"password": "some_password",
}
}
do_thing()
mock_psycopg2.connect.assert_called_with("some database")
...
It seems that the problem here is that it's too late to mock something by the time the module with do_thing() has already been imported. You can try the following trick:
import sys
from unittest.mock import MagicMock
psycopg2_mock = MagicMock()
sys.modules['psycopg2'] = psycopg2_mock
import module_with_do_thing
del sys.modules['psycopg2']
class TestSomething(unittest.TestCase):
...
def test_attempts_to_connect_to_redshift(self):
...
assert psycopg2_mock.has_required_properties
Moving the import module_with_do_thing line to the actual test method with the right patch might work as well.

Import not working with typescript

I'm importing object to a .ts file but it is undefined, when I do the same with require keyword , then it is working. But I'd like to understand whats happening
const jwt = require('jsonwebtoken'); // working
import {jwt2} from 'jsonwebtoken'; // not working
The first example is importing the entire module, while the second one is trying to import a member of the module named jwt2, but there is no such member. To import the entire module using import, try:
import * as jwt2 from 'jsonwebtoken';

ES6 - Duplicate declaration on importing files

in pre-es6:
var stream = require("./models/stream");
var stream = require("./routes/stream");
It works fine.
In es6:
import stream from './models/stream';
import stream from './routes/stream';
Error:
TypeError: /var/www/.../es6/app.js: Duplicate declaration "stream"
> 31 | import stream from './routes/stream';
Any ideas how can I import it properly?
Use different module names
import stream from './models/stream';
import streamroutes from './routes/stream';
You are re-declaring the stream variable and never use it, so you can just import first file without assignment:
import './models/stream';
import stream from './routes/stream';

Resources