Skip to content

Commit 992edb1

Browse files
committed
created copilot-instructions.md file
1 parent 44086f8 commit 992edb1

1 file changed

Lines changed: 162 additions & 0 deletions

File tree

.github/copilot-instructions.md

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
# RKD Python Project Instructions
2+
3+
## Overview
4+
This project contains Python scripts for the Knowledge Direct (RKD) API client. All code follows a functional, service-oriented architecture pattern with REST/WebSocket authentication and request handling.
5+
6+
---
7+
8+
## Code Quality Standards
9+
10+
### 1. **Function Organization**
11+
- Use **function-based design** (no classes unless absolutely necessary for WebSocket handlers)
12+
- Organize code in logical flow: **Credentials → Authentication → Service Requests**
13+
- Always include `if __name__ == '__main__':` entry point in executable scripts
14+
- Extract repeated logic into reusable helper functions (e.g., `doSendRequest()` for HTTP operations)
15+
16+
### 2. **Naming Conventions**
17+
- Function names: `PascalCase` for API-related functions (e.g., `CreateAuthorization()`, `RetrieveQuotes()`)
18+
- Variable names: `snake_case` for standard variables
19+
- Constants: `UPPER_SNAKE_CASE`
20+
- Avoid abbreviations; be explicit (e.g., `token_endpoint` not `tk_ep`)
21+
22+
### 3. **Documentation Requirements**
23+
- **Legal notice**: Include the triple-quoted disclaimer block at the top of every file
24+
- **Function docstrings**: Add docstrings to ALL functions in Google style:
25+
```python
26+
def RetrieveQuotes(token, ric_list):
27+
"""Fetch quote data for given RICs from the Quote service.
28+
29+
Args:
30+
token (str): Authentication token from CreateAuthorization()
31+
ric_list (list): List of RIC codes (e.g., ['AAPL.O', 'IBM.N'])
32+
33+
Returns:
34+
dict: JSON response containing quote data, or None on failure
35+
"""
36+
```
37+
- **Section headers**: Use `## -------- Description --------` format for logical sections
38+
- **Inline comments**: Explain *why*, not *what*; use `#` prefix
39+
40+
### 4. **Error Handling**
41+
- Wrap HTTP requests in try-except blocks catching `requests.exceptions.RequestException`
42+
- Check HTTP status codes: `if result.status_code == 200` for success
43+
- Print descriptive error messages to aid debugging
44+
- Exit gracefully with `sys.exit(1)` on fatal errors
45+
- Always call `result.raise_for_status()` for non-200 responses
46+
47+
**Example pattern:**
48+
```python
49+
try:
50+
result = doSendRequest(url, headers, body)
51+
if result.status_code == 200:
52+
return result.json()
53+
else:
54+
print(f"Error: {result.status_code} - {result.text}")
55+
sys.exit(1)
56+
except requests.exceptions.RequestException as e:
57+
print(f"Request failed: {e}")
58+
sys.exit(1)
59+
```
60+
61+
---
62+
63+
## Authentication Pattern (CRITICAL)
64+
65+
### Token-Based Authentication
66+
1. **Credential Loading Priority:**
67+
- Environment variables from `.env` file (via `python-dotenv`)
68+
- User input via `getpass.getpass()` (passwords only, never print)
69+
- Fail gracefully if credentials unavailable
70+
71+
2. **Header Format:**
72+
- `X-Trkd-Auth-Token`: OAuth token from `CreateAuthorization()`
73+
- `X-Trkd-Auth-ApplicationID`: Application identifier
74+
- Include in all service requests
75+
76+
3. **Token Lifecycle:**
77+
- Call `CreateAuthorization()` once per session
78+
- Token expires (include expiration check if token returned expiry)
79+
- Handle token refresh if service requires re-authentication
80+
81+
**Example:**
82+
```python
83+
# Load credentials
84+
username = os.getenv('TRKD_USERNAME')
85+
password = getpass.getpass("Enter password: ")
86+
87+
# Get token
88+
token = CreateAuthorization(username, password)
89+
90+
# Use token in all subsequent requests
91+
headers = {
92+
'X-Trkd-Auth-Token': token,
93+
'X-Trkd-Auth-ApplicationID': app_id,
94+
'Content-Type': 'application/json'
95+
}
96+
```
97+
98+
---
99+
100+
## Code Style & Implementation
101+
102+
### Imports
103+
- Group in standard order: standard library → third-party → local modules
104+
- Place all imports at the top of file (except dynamic imports in specific functions)
105+
106+
### Logging
107+
- Use `print()` statements for output (established pattern in project)
108+
- Format informative messages for users running scripts
109+
- Print errors to stderr; use explicit status messages
110+
111+
### HTTP Requests
112+
- Use the `doSendRequest()` helper function to abstract POST logic
113+
- Pass URL, headers dict, and JSON body separately
114+
- Always set `'Content-Type': 'application/json'` in headers
115+
- Use `json=` parameter in `requests.post()`, not `data=`
116+
117+
### Credential Management
118+
- Never hardcode credentials in source code
119+
- Always load from environment variables or user input
120+
- Use `getpass.getpass()` for password input (doesn't echo to terminal)
121+
- Load `.env` file at script start with `load_dotenv()`
122+
123+
---
124+
125+
## When Making Changes
126+
127+
### Adding New Features
128+
1. Follow the function-first design pattern
129+
2. Add docstrings immediately (required)
130+
3. Implement error handling around HTTP operations
131+
4. Test with both successful and failed API responses
132+
5. Update README with usage examples
133+
134+
### Modifying Existing Functions
135+
- Maintain the authentication pattern
136+
- Keep `try-except` structure around requests
137+
- Preserve section header comments
138+
- Update docstrings if parameters/return values change
139+
140+
### Creating New Scripts
141+
- Copy the legal disclaimer from existing files
142+
- Include `if __name__ == '__main__':` entry point
143+
- Organize: imports → functions → main block
144+
- Load credentials early, authenticate once
145+
146+
---
147+
148+
## Dependencies
149+
- `requests`: HTTP/REST operations
150+
- `websocket-client`: WebSocket streaming (for *_wsstreaming*.py scripts)
151+
- `python-dotenv`: Environment variable loading from `.env`
152+
- `python-dateutil`: Date parsing and manipulation
153+
- Standard library: `json`, `sys`, `os`, `getpass`, `threading`, `time`
154+
155+
---
156+
157+
## Explanation Principles
158+
When working with this codebase, prioritize clarity and educational value:
159+
- **Explain the 'why'**: Decisions about authentication flow, error handling, or architecture
160+
- **Reference patterns**: Point to existing examples when introducing patterns
161+
- **Be thorough**: Describe impacts on existing code or token lifecycle
162+
- **Document trade-offs**: If suggesting alternatives, explain the rationale

0 commit comments

Comments
 (0)